Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Sorting Algorithms Unit-4

PPS

Uploaded by

pragya.gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Sorting Algorithms Unit-4

PPS

Uploaded by

pragya.gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

SORTING:

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.

How does Selection Sort Algorithm work?


Lets consider the following array as an 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 is 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 is 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 traverse 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.

Algorithm

SELECTION SORT(arr, n)
Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
Step 2: CALL SMALLEST(arr, i, n, pos)
Step 3: SWAP arr[i] with arr[pos]
[END OF LOOP]
Step 4: EXIT

SMALLEST (arr, i, n, pos)


Step 1: [INITIALIZE] SET SMALL = arr[i]
Step 2: [INITIALIZE] SET pos = i
Step 3: Repeat for j = i+1 to n
if (SMALL > arr[j])
SET SMALL = arr[j]
SET pos = j
[END OF if]
[END OF LOOP]
Step 4: RETURN pos

Implementation of selection sort


Now, let's see the programs of selection sort in different programming languages.
Program: Write a program to implement selection sort in C language.

1. #include <stdio.h>
2.
3. void selection(int arr[], int n)
4. {
5. int i, j, small;
6.
7. for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
8. {
9. small = i; //minimum element in unsorted array
10.
11. for (j = i+1; j < n; j++)
12. if (arr[j] < arr[small])
13. small = j;
14. // Swap the minimum element with the first element
15. int temp = arr[small];
16. arr[small] = arr[i];
17. arr[i] = temp;
18. }
19. }
20.
21. void printArr(int a[], int n) /* function to print the array */
22. {
23. int i;
24. for (i = 0; i < n; i++)
25. printf("%d ", a[i]);
26. }
27.
28. int main()
29. {
30. int a[] = { 12, 31, 25, 8, 32, 17 };
31. int n = sizeof(a) / sizeof(a[0]);
32. printf("Before sorting array elements are - \n");
33. printArr(a, n);
34. selection(a, n);
35. printf("\nAfter sorting array elements are - \n");
36. printArr(a, n);
37. return 0;
38. }

Time Complexity
Case Time Complexity
Best Case O(n2)
Average Case O(n2)
Worst Case O(n2)
o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is
already sorted. The best-case time complexity of selection sort is O(n2).
o 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 selection sort is O(n2).
o 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
selection sort is O(n2).
2. Space Complexity
Space Complexity O(1)
Stable YES
o The space complexity of selection sort is O(1). It is because, in selection sort, an extra
variable is required for swapping.

BUBBLE SORT

Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the
intended order. It is called bubble sort because the movement of array elements is just like the
movement of air bubbles in the water. Bubbles in water rise up to the surface; similarly, the
array elements in bubble sort move to the end in each iteration.

Algorithm
In the algorithm given below, suppose arr is an array of n elements. The
assumed swap function in the algorithm will swap the values of given array elements.

1. begin BubbleSort(arr)
2. for all array elements
3. if arr[i] > arr[i+1]
4. swap(arr[i], arr[i+1])
5. end if
6. end for
7. return arr
8. end BubbleSort

Working of Bubble sort Algorithm


Now, let's see the working of Bubble sort Algorithm.
To understand the working of bubble sort algorithm, let's take an unsorted array. We
are taking a short and accurate array, as we know the complexity of bubble sort
is O(n2).
Let the elements of array are -

First Pass
Sorting will start from the initial two elements. Let compare them to check which is
greater.

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 -

Now, compare 32 and 35.

Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.
Now, the comparison will be in between 35 and 10.

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.

Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -

Now, move to the third iteration.

Third Pass
The same process will be followed for third iteration.
Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be -

Now, move to the fourth iteration.

Fourth pass
Similarly, after the fourth iteration, the array will be -

Hence, there is no swapping required, so the array is completely sorted.

Bubble sort complexity


Now, let's see the time complexity of bubble sort in the best case, average case, and
worst case. We will also see the space complexity of bubble sort.

1. Time Complexity
Case Time Complexity

Best Case O(n)

Average Case O(n2)

Worst Case O(n2)


o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is
already sorted. The best-case time complexity of bubble sort is O(n).
o 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 bubble sort is O(n2).
o 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).

2. Space Complexity
Space Complexity O(1)

Stable YES
o The space complexity of bubble sort is O(1). It is because, in bubble sort, an extra
variable is required for swapping.
o The space complexity of optimized bubble sort is O(2). It is because two extra variables
are required in optimized bubble sort.

Now, let's discuss the optimized bubble sort algorithm.

Optimized Bubble sort Algorithm


In the bubble sort algorithm, comparisons are made even when the array is already
sorted. Because of that, the execution time increases.
To solve it, we can use an extra variable swapped. It is set to true if swapping requires;
otherwise, it is set to false.
It will be helpful, as suppose after iteration, if there is no swapping required, the value
of variable swapped will be false. It means that the elements are already sorted, and no
further iterations are required.
This method will reduce the execution time and also optimizes the bubble sort.

Algorithm for optimized bubble sort


1. bubbleSort(array)
2. n = length(array)
3. repeat{
4. swapped = false
5. for i = 1 to n - 1
6. if array[i - 1] > array[i], then
7. swap(array[i - 1], array[i])
8. swapped = true
9. end if
10. end for
11. n=n-1
12. } Until (swapped ==true)
13. end bubbleSort

Program: Write a program to implement bubble sort in C language.


#include<stdio.h>
void print(int a[], int n) //function to print array elements
{
int i;
for(i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
}
void bubble(int a[], int n) // function to implement bubble sort
{
int i, j, temp;
boolean swap= true;
for(i = 0; i < n && swap==true; i++)
{
swapped =false;
for(j = i+1; j < n; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
swapped = true;
}
}
}
}
void main ()
{
int i, j,temp;
int a[5] = { 10, 35, 32, 13, 26};
int n = sizeof(a)/sizeof(a[0]);
printf("Before sorting array elements are - \n");
print(a, n);
bubble(a, n);
printf("\nAfter sorting array elements are - \n");
print(a, n);
}

Output

Insertion Sort Algorithm


● Insertion sort works similar to the sorting of playing cards in hands. It is
assumed that the first card is already sorted in the card game, and then we
select an unsorted card.
● If the selected unsorted card is greater than the first card, it will be placed at the
right side; otherwise, it will be placed at the left side. Similarly, all unsorted
cards are taken and put in their exact place.
● 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 as the 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.
Insertion sort has various advantages such as -

Algorithm for Insertion Sort in C Language

● We iterate over the array from arr[1] to arr[n - 1].


● In each iteration, we compare the current element to its predecessor.
● If the current element is smaller than its predecessor, compare it to the elements before
it. All the elements greater than the current element are shifted and the current element
is placed at its correct position.

C Language Program for Insertion Sort:


#include <stdio.h>

void insertionSort(int arr[], int n) {

for (int step = 1; step < n; step++) {

int x = arr[step];

int j = step - 1;

while (x < arr[j] && j >= 0) {

arr[j + 1] = arr[j];

--j;

arr[j + 1] = x;

void printArray(int arr[], int size) {

for (int i = 0; i < size; ++i) {

printf("%d ", arr[i]);

printf("\n");

int main() {
int arr[10000];

int n;

printf("Enter size of the array: ");

scanf("%d", &n);

printf("Enter the array elements: ");

for(int i = 0; i < n; i++)

scanf("%d", &arr[i]);

insertionSort(arr, n);

printf("After sorting, the array is: ");

printArray(arr, n);

Copy

Enter size of the array: 5

Enter the array elements: 0 -45 34 56 4

After sorting, the array is: -45 0 4 34 56

Time Complexity
The worst case time complexity of insertion sort in O(\(n^2\)). The best case time
complexity is O(n) and the average case time complexity is also O(n).

Insertion Sort
The logic used to sort the elements by using the insertion sort technique is as
follows −

for(i = 1; i <= n - 1; i++)


{
for(j = i; j > 0 && a[j - 1] > a[j]; j--)
{
t = a[j];
a[j] = a[j - 1];
a[j - 1] = t;
}
}
Explanation
Let us consider some elements which are in unsorted order −

Example
Following is the C program to sort the elements by using the insertion sort
technique −

#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(i=0; i<n; i++){
scanf ("%d", &a[i]);
}
for(i = 1; i <= n - 1; i++){
for(j=i; j > 0 && a[j - 1] > a[j]; j--){
t = a[j];
a[j] = a[j - 1];
a[j - 1] = t;
}
}
printf ("after insertion sorting the elements are:
");
for (i=0; i<n; i++)
printf("%d\t", a[i]);
return 0;
}
Output
When the above program is executed, it produces the following output −

Enter the No: of elements in the list:


10
Enter the elements:
34
125
2
6
78
49
1
3
89
23
After insertion sorting the elements are:
1 2 3 6 23 34 49 78 89 125

You might also like