DS - Unit V - Sorting
DS - Unit V - Sorting
DS - Unit V - Sorting
so that they can be placed either in ascending or descending order. For example,
consider an array A = {A1, A2, A3, A4, ?? An }, the array is called to be in ascending
order if element of A are arranged like A1 > A2 > A3 > A4 > A5 > ? > An .
Consider an array;
Sorting Algorithms
Sorting algorithms are described in the following table along with the
description.
SN Sorting Description
Algorithms
return list
end BubbleSort
Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless
the whole array is completely sorted in an ascending order. This may cause a few
complexity issues like what if the array needs no more swapping as all the elements are
already ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any
swap has happened or not. If no swap has occurred, i.e. the array requires no more
processing to be sorted, it will come out of the loop.
Pseudocode of BubbleSort algorithm can be written as follows −
procedure bubbleSort( list : array of items )
loop = list.count;
end for
end for
Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare
32 with 26.
Here, 26 is smaller than 36. So, swapping is required. After swapping new
array will look like -
Here, 35 is greater than 32. So, there is no swapping required as they are
already sorted.
Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now,
we reach at the end of the array. After first pass, the array will be -
Now, move to the second iteration.
Second Pass
The same process will be followed for second iteration.
Third Pass
The same process will be followed for third iteration.
Fourth pass
Similarly, after the fourth iteration, the array will be -
Time Complexity
Case Time Complexity
that is not properly ascending and not properly descending. The average case
time complexity of bubble sort is O(n2).
• Worst Case Complexity - It occurs when the array elements are required to be
sorted in reverse order. That means suppose you have to sort the array
elements in ascending order, but its elements are in descending order. The
worst-case time complexity of bubble sort is O(n2).
Space Complexity
Stable YES
o The space complexity of optimized bubble sort is O(2). It is because two extra
variables are required in optimized bubble sort.
Output
2. Insertion Sort Algorithm
The same approach is applied in insertion sort. The idea behind the
insertion sort is that first take one element, iterate it through the sorted
array.
Although it is simple to use, it is not appropriate for large data sets.
Time complexity of insertion sort in the average case and worst case is
O(n2), where n is the number of items.
Insertion sort is less efficient than the other sorting algorithms like heap
sort, quick sort, merge sort, etc.
o Simple implementation
o Efficient for small data sets
o Adaptive, i.e., it is appropriate for data sets that
are already substantially sorted.
Step3 - Now, compare the key with all elements in the sorted
array.
Pseudocode
end for
end procedure
Here, 31 is greater than 12. That means both elements are already in
ascending order. So, for now, 12 is stored in a sorted sub-array.
For now, the sorted array has only one element, i.e. 12. So, 25 is greater than
12. Hence, the sorted array remains sorted after swapping.
Now, two elements in the sorted array are 12 and 25. Move forward to the
next elements that are 31 and 8.
Now, the sorted array has three items that are 8, 12 and 25. Move to the next
items that are 31 and 32.
Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and
31.
Now, let’s see the time complexity of insertion sort in best case, average case,
and in worst case. We will also see the space complexity of insertion sort.
1. Time Complexity
Best Case Complexity – It occurs when there is no sorting required, i.e. the
array is already sorted. The best-case time complexity of insertion sort is O(n).
Average Case Complexity – It occurs when the array elements are in jumbled
order that is not properly ascending and not properly descending. The average
case time complexity of insertion sort is O(n2).
Worst Case Complexity – It occurs when the array elements are required to
be sorted in reverse order. That means suppose you have to sort the array
elements in ascending order, but its elements are in descending order. The
worst-case time complexity of insertion sort is O(n2).
2. Space Complexity
Stable YES
int i, j, temp;
int n = a.length;
{ temp = a[i];
J = i – 1;
While(j>=0 && temp <= a[j]) /* Move the elements greater than temp
to one position ahead from their current position*/
A[j+1] = a[j];
J = j-1;
A[j+1] = temp;
int i;
int n = a.length;
System.out.print(a[i] + “ “);
i1.printArr(a);
i1.insert(a);
i1.printArr(a);
System.out.println();
Output:
3. SELECTION SORT:
Algorithm
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
Pseudocode
procedure selection sort
list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
end procedure
How Selection Sort Works?
Consider the following depicted array as an example.
For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the
lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value
in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a
linear manner.
We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −
4. SHELL SORT:
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm. This algorithm
avoids large shifts as in case of insertion sort, if the smaller value is to the far right and has to be moved
to the far left.
This algorithm uses insertion sort on a widely spread elements, first to sort them and then sorts the less
widely spaced elements. This spacing is termed as interval. This interval is calculated based on Knuth’s
formula as –
Knuth’s Formula
H=h*3+1
Where –
This algorithm is quite efficient for medium-sized data sets as its average and worst-case complexity of
this algorithm depends on the gap sequence the best known is Ο(n), where n is the number of items.
And the worst case space complexity is O(n).
Algorithm
Following is the algorithm for shell sort.
Step 1 − Initialize the value of h
Step 2 − Divide the list into smaller sub-list of equal interval h
Step 3 − Sort these sub-lists using insertion sort
Step 3 − Repeat until complete list is sorted
Pseudocode
Following is the pseudocode for shell sort.
procedure shellSort()
A : array of items
/* calculate interval*/
while interval < A.length /3 do:
interval = interval * 3 + 1
end while
end for
/* calculate interval*/
interval = (interval -1) /3;
end while
end procedure
How Shell Sort Works?
Let us consider the following example to have an idea of how shell sort works. We take
the same array we have used in our previous examples. For our example and ease of
understanding, we take the interval of 4. Make a virtual sub-list of all values located at
the interval of 4 positions. Here these values are {35, 14}, {33, 19}, {42, 27} and {10, 44}
We compare values in each sub-list and swap them (if necessary) in the original array.
After this step, the new array should look like this −
Then, we take interval of 1 and this gap generates two sub-lists - {14, 27, 35, 42}, {19,
10, 33, 44}
We compare and swap the values, if required, in the original array. After this step, the
array should look like this –
Finally, we sort the rest of the array using interval of value 1. Shell sort uses insertion
sort to sort the array.
Import java.util.*;
Int i, j, k, tmp;
For(k = j – i; k>= 0; k = k – i)
Break;
Else
Tmp = arr[k];
Arr[k] = arr[k+i];
Arr[k+i] = tmp;
{
Scanner sc = new Scanner(System.in);
Intk, num;
Num = sc.nextInt();
Arr[k]=sc.nextInt();
Shellsort(arr, num);
System.out.println(arr[k]);
Output:
10
Radix sort is the linear sorting algorithm that is used for integers.
In Radix sort, there is digit by digit sorting is performed that is started from the
least significant digit to the most significant digit.
1. radixSort(arr)
5. for i -> 0 to d
6. sort the array elements using counting sort (or any stable sort) according to the
In the given array, the largest element is 736 that have 3 digits in it.
So, the loop will run up to three times (i.e., to the hundreds place). That means
three passes are required to sort the array.
Now, first sort the elements on the basis of unit place digits (i.e., x = 0). Here,
we are using the counting sort algorithm to sort the elements.
Pass 1:
In the first pass, the list is sorted on the basis of the digits at 0's place.
Pass 2:
In this pass, the list is sorted on the basis of the next significant digits (i.e.,
digits at 10th place).
After the second pass, the array elements are -
Pass 3:
In this pass, the list is sorted on the basis of the next significant digits (i.e.,
digits at 100th place).
After the third pass, the array elements are -
1. class RadixSort {
2.
7. max = a[i];
8. }
9. return max; //maximum element from the array
10. }
11.
12. void countingSort(int a[], int n, int place) // function to implement counting
13.
14. sort
15. {
18.
22.
26.
31. }
32.
35. }
36.
39.
42.
46. }
47.
52. }
53.
55. int a[] = {151, 259, 360, 91, 115, 706, 34, 858, 2};
59. r1.printArray(a,n);
62.
63. \n");
65. }
66. }
Output: