Unit 3 Sorting
Unit 3 Sorting
In this algorithm,
Traverse from left and compare adjacent elements and the higher one is placed
at right side.
In this way, the largest element is moved to the rightmost end at first.
This process is then continued to find the second largest and place it and so on
until the data is sorted.
This algorithm has a worst-case time complexity of O(n2). The bubble sort has
a space complexity of O(1).
Example-
Input: arr[] = {6, 3, 0, 5}
First Pass:
The largest element is placed in its correct position, i.e., the end of the array.
Second Pass:
Place the second largest element at correct position
Third Pass:
Place the remaining two elements at their correct positions.
Bubble Sort Implementation-
#include<stdio.h>
int main(){
int a[50], i,j,n,t;
printf("enter the No of elements in the list:");
scanf("%d", &n);
printf("enter the elements for sorting:");
for(i=0; i<n; i++){
scanf ("%d", &a[i]);
}
printf("Before bubble sorting the elements are:");
for(i=0; i<n; i++)
printf("%d \t", a[i]);
for (i=0; i<n-1; i++){
for (j=i+1; j<n; j++){
if (a[i] > a[j]){
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
printf ("\nAfter bubble sorting the elements are:");
for (i=0; i<n; i++)
printf("%d\t", a[i]);
return 0;
}
Selection Sort
Selection sort is a simple and efficient sorting algorithm that works by repeatedly
selecting the smallest (or largest) element from the unsorted portion of the list and
moving it to the sorted portion of the list.
example:
arr[] = {64, 25, 12, 22, 11}
First pass:
For the first position in the sorted array, the whole array is traversed from index
0 to 4 sequentially. The first position where 64 are stored presently, after
traversing whole array it is clear that 11 is the lowest value.
Thus, replace 64 with 11. After one iteration 11, which happens to be the least
value in the array, tends to appear in the first position of the sorted list.
Second Pass:
For the second position, where 25 are present, again traverse the rest of the array
in a sequential manner.
After traversing, we found that 12 is the second lowest value in the array and it
should appear at the second place in the array, thus swap these values.
Third Pass:
Now, for third place, where 25 is present again traversing the rest of the array
and find the third least value present in the array.
While traversing, 22 came out to be the third least value and it should appear at
the third place in the array, thus swap 22 with element present at third position.
Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the fourth
least element in the array
As 25 is the 4th lowest value hence, it will place at the fourth position.
Fifth Pass:
At last the largest value present in the array automatically get placed at the last
position in the array
The resulted array is the sorted array.
Insertion sort is a simple sorting algorithm that works similar to the way you sort
playing cards in your hands. The array is virtually split into a sorted and an
unsorted part. Values from the unsorted part are picked and placed at the correct
position in the sorted part.
To sort an array of size N in ascending order iterate over the array and
compare the current element (key) to its predecessor,
If the key element is smaller than its predecessor, compare it to the elements
before.
Move the greater elements one position up to make space for the swapped
element.
12 11 13 5 6
First Pass:
Initially, the first two elements of the array are compared in insertion sort.
12 11 13 5 6
Here, 12 is greater than 11 hence they are not in the ascending order and 12 is
not at its correct position. Thus, swap 11 and 12.
So, for now 11 is stored in a sorted sub-array.
11 12 13 5 6
Second Pass:
Now, move to the next two elements and compare them
11 12 13 5 6
Here, 13 is greater than 12, thus both elements seems to be in ascending order,
hence, no swapping will occur. 12 also stored in a sorted sub-array along with
11
Third Pass:
Now, two elements are present in the sorted sub-array which are 11 and 12
Moving forward to the next two elements which are 13 and 5
11 12 13 5 6
Both 5 and 13 are not present at their correct place so swap them
11 12 5 13 6
After swapping, elements 12 and 5 are not sorted, thus swap again
11 5 12 13 6
5 11 12 13 6
Fourth Pass:
Now, the elements which are present in the sorted sub-array are 5, 11 and 12
Moving to the next two elements 13 and 6
5 11 12 13 6
Clearly, they are not sorted, thus perform swap between both
5 11 12 6 13
5 11 6 12 13
5 6 11 12 13
Implementation-
#include <stdio.h>
// Function to print an array
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
// Driver code
int main() {
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
printf("array before sorting:\n");
printArray(data, size);
insertionSort(data, size);
printf("Sorted array in ascending order:\n");
printArray(data, size);
}
Quick Sort
Divide: In Divide, first pick a pivot element. After that, partition or rearrange the
array into two sub-arrays such that each element in the left sub-array is less than or
equal to the pivot element and each element in the right sub-array is larger than the
pivot element.
Now, in a similar manner, quick sort algorithm is separately applied to the left and
right sub-arrays.
10 30 40 80 90
Time Complexity:
Best Case: Ω (N log (N))
Merge sort is defined as a sorting algorithm that works by dividing an array into
smaller sub arrays, sorting each sub array, and then merging the sorted sub
arrays back together to form the final sorted array. With worst-case time
complexity being Ο(n log n), it is one of the most respected algorithms.
Merge sort is similar to the quick sort algorithm as it uses the divide and conquer
approach to sort the elements. It is one of the most popular and efficient sorting
algorithm. It divides the given list into two equal halves, calls itself for the two
halves and then merges the two sorted halves
Time complexity of Merge Sort is O(n*Log n) in all the 3 cases (worst, average
and best) as merge sort always divides the array in two halves and takes linear
time to merge two halves.
Merge sort first divides the whole array iteratively into equal halves unless
the atomic values are achieved. Now, an array of 8 items is divided into two
arrays of size 4.
This does not change the sequence of appearance of items in the original.
Now divide these two arrays into halves.
Further divide these arrays and achieve atomic value which can no more be
divided.
Now, combine them in exactly the same manner as they were broken down.
First compare the element for each list and then combine them into another
list in a sorted manner. Now, 14 and 33 are in sorted positions. Compare 27
and 10 and in the target list of 2 values we put 10 first, followed by 27. Let
change the order of 19 and 35 whereas 42 and 44 are placed sequentially.
In the next iteration of the combining phase, compare lists of two data
values, and merge them into a list of found data values placing all in a sorted
order.
After the final merging, the list should look like this −
#include <stdio.h>
// Until we reach either end of either L or M, pick larger among elements L and M
and place them in the correct position at A[p..r]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}
// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r) {
// Driver program
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: \n");
printArray(arr, size);
mergeSort(arr, 0, size - 1);
printf("Sorted array after merge sort: \n");
printArray(arr, size);}
Radix Sort Algorithm
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.
Example-
The process of radix sort works similar to the sorting of students names, according
to the alphabetical order. In this case, there are 26 radix formed due to the 26
alphabets in English. In the first pass, the names of students are grouped according
to the ascending order of the first letter of their names. After that, in the second
pass, their names are grouped according to the ascending order of the second letter
of their name. And the process continues until we find the sorted list.
Pass 1:
In the first pass, the list is sorted on the basis of the digits at 0's place.
After the first pass, the array elements are -
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 -
Now, let's see the time complexity of Radix sort in best case, average case, and
worst case. We will also see the space complexity of Radix sort.
1. Time Complexity
Case Time Complexity
2. Space Complexity
Space Complexity O(n + k)
Stable YES
#include <stdio.h>
max = array[i];
return max;
// Using counting sort to sort the elements in the basis of significant places
max = array[i];
count[i] = 0;
array[i] = output[i];
// Print an array
printf("\n");
// Driver code
int main() {
radixsort(array, n);
printArray(array, n);