Selection Sort
Selection sort algorithm sorts an array by reapetly finding the minimum element (considering ascending order) from unsorted port and putting it at the beginning.
Complexity of Selection Sort:
- Time Complexity
- Best Case: O(n2)
- Worst Case: O(n2)
- Space Complexity
- Worst Case: O(1)
- Advantages of Selection Sort
- Selction sort algorithm easy to implement.
- No additional data-structure is required.
- It is in-place sorting method & stable method.
- The number of swap reduced.O(n) swap in all cases.
- Disadvantages of Selction Sort
- Best & Worst case efficiency is O(n2).
CODE
👇
- #include <stdio.h>
- int comp_cnt=0;
- int main()
- {
- int a[20], n , i;
- printf("\t>>Selection Sort<<\n");
- printf("How many numbers you want in array ?\t");
- scanf("%d",&n);
- printf("\nEnter %d element:",n);
- accept(a,n);
- selection_sort(a,n);
- printf("\t>>Sorted Array<<\n");
- display(a,n);
- printf("\nTotal number of comparisons = %d", comp_cnt);
- return 0;
- }
- void accept(int a[], int n)
- {
- int i;
- for(i=0; i<n; i++)
- scanf("%d", &a[i]);
- }
- void display(int a[], int n)
- {
- int i;
- for(i=0; i<n; i++)
- printf("%d\t",a[i]);
- }
- void selection_sort(int a[], int n)
- {
- int i, temp, current, pos, smallest;
- for(current=0; current<n-1; current++)
- {
- smallest = a[current];
- pos = current;
- for(i=current+1; i<=n-1; i++, comp_cnt++)
- if(a[i] < smallest)
- {
- smallest = a[i];
- pos = i;
- }
- temp = a[current];
- a[current] = a[pos];
- a[pos] = temp;
- }
- }
👉Execute👈
//Output
/*
>>Selection Sort<<
How many numbers you want in array ? 5
Enter 5 element:47
78
26
64
29
>>Sorted Array<<
26 29 47 64 78
Total number of comparisons = 10
*/
//ThE ProFessoR
Comments
Post a Comment