# Array Computer Solutions: Sorting: Bubble and Selection Sort

Glide to success with Doorsteptutor material for CBSE/Class-9 Science: fully solved questions with step-by-step explanation- practice your way to success.

Download PDF of This Page (Size: 358K) ↧

### Sorting

It is a method to arrange the list either in ascending or descending order.

#### Bubble Sort

Consider an array of five locations to be sorted in ascending order:

In this sorting method, A [0] is compared with A [1].

If A [0] is greater than A [1], the values are swapped.

Then A [1] is compared with A [2], A [2] is compared with A [3], and A [3] is compared with A [4].

In all cases if the i

^{th}location has value greater than I + 1, the values are swapped.

The entire process is repeated N-1 times where N is the number of data in an array.

# include < iostream.h >

const int N = 5.

void main ()

{

int A [N], l, j, T.

cout << “Enter values”.

for (l = 0; l = N; l ++)

cin >> A [l].

/ / sorting

for (l = 0; l < N - 1; l ++)

for (j = 0; j < N - 1; j ++)

If (A[j] > A [j + 1])

{

T = A [j].

A [j] = A [j + 1].

A [j + 1] = T.

}

cout << “Sorted array is”.

for (l = 0; I < N; l ++)

cout << A [l].

}

#### Selection Sort

Consider an array having N elements to be sorted in ascending order.

Initially, first element is compared with others so that it holds the smallest value.

In the next pass, second element is compared with others so that it holds the smallest value. This procedure is repeated for the entire array.

# include < iostream.h >

const int N = 5.

void main ()

{

int A [N], l, j, T.

cout << “Enter values”.

for (l = 0; l < N; l ++)

cin >> A [l].

/ / sorting

for (l = 0; l < N - 1; l ++)

for (j = l; j < N; j ++)

If (A [l] > A [j])

{

T = A [l].

A [l] = A [j].

A [j] = T.

}

// printing the sorted data

for (l = 0; l < N; l ++)

cout < < A [l].

}