# 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.

### 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  is compared with A .

• If A  is greater than A , the values are swapped.

• Then A  is compared with A , A  is compared with A , and A  is compared with A .

• In all cases if the ith 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].

}

Developed by: