Array Sorting
Shorting: Sometimes we need to short out a list of elements by ascending order or
descending order. For this purpose we can apply various shorting algorithms.
1. Insertion sort
2. Bubble sort
3. Merge sort
4. Quick sort
5. Radix sort
6. Heap sort
7. Selection sort
Bubble sort:
int a[50], i, j, n, temp;
scanf(“%d”,&n);
for( i = 0; i < n; i ++)
scanf(“%d”, & a[i]);
for( i = 0; i < n-1; i ++)
for( j = i+1; j < n; j ++)
if( a[i] > a[j]){
temp = a[ i ]; Shorting logic
a[i] = a[ j ];
a[ j ] = temp;
}
for( i = 0; i < n; i ++)
printf(“%d”, a[i]);
}
Example: Suppose that we have a list of 5 elements. We will use the bubblseort
algorithm to sort the given list in ascending order.
0 1 2 3 4
a 10 5 7 3 2
Pass one: i = 0, j=1
(a[0] > a[1]) TRUE
0 1 2 3 4
a 5 10 7 3 2
j=2
(a[0] > a[2]) FALSE
0 1 2 3 4
a 5 10 7 3 2
j=3
(a[0] > a[3]) TRUE
0 1 2 3 4
a 3 10 7 5 2
j=4
(a[0] > a[4]) TRUE
0 1 2 3 4
a 2 10 7 5 3
Pass two: i = 1, j=2
(a[1] > a[2]) TRUE
0 1 2 3 4
a 2 7 10 5 3
j=3
(a[1] > a[3]) TRUE
0 1 2 3 4
a 2 5 10 7 3
j=4
(a[1] > a[4]) TRUE
0 1 2 3 4
a 2 3 10 7 5
Pass three: i = 2, j=3
(a[2] > a[3]) TRUE
0 1 2 3 4
a 2 3 7 10 5
j=4
(a[2] > a[4]) TRUE
0 1 2 3 4
a 2 3 5 10 7
Pass four: i = 3, j=4
(a[3] > a[4]) TRUE
0 1 2 3 4
a 2 3 5 7 10
SELF-STUDY: 2D Array declaration, Input and Output. (Must)