Selecting Sort
Just like Bubble sort, selection sort has also a time complexity of O(n2) . Selection sort scans through the list iteratively, selects one item and places that item at its correct position in the list.
The efficiency of the algorithm is compared in terms of number of comparisons.
In selection sort algorithm there is (n-1) comparisons in first loop, (n-2) comparisons in second loop and so on.
So, there is total of (n-1) + (n-2) + ..... + 2 + 1 comparisons. Thus, the total no. of comparisons are
n*(n-1)/2. Thus, leading to the time complexity of O(n2).
The code for the selection sort is as follows:
The efficiency of the algorithm is compared in terms of number of comparisons.
In selection sort algorithm there is (n-1) comparisons in first loop, (n-2) comparisons in second loop and so on.
So, there is total of (n-1) + (n-2) + ..... + 2 + 1 comparisons. Thus, the total no. of comparisons are
n*(n-1)/2. Thus, leading to the time complexity of O(n2).
The code for the selection sort is as follows:
//SELCETIONSORT #include<stdio.h> #define MAX 5 void selectionsort(int *,int *); void display(int *,int *); int main() { int a[MAX],n,i; printf("Enter the no. of elements in the array,where MAX=%d: ",MAX); scanf("%d",&n); for(;n>MAX;scanf("%d",&n)) printf("The value entered is greater than MAX.Please re-enter the value: "); printf("Enter the elements of the array: \n"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("The unsorted array: "); display(a,a+n); printf("\n"); selectionsort(a,a+n); printf("The sorted array: "); display(a,a+n); return 0; } void selectionsort(int *p,int *q) { if(p!=q) { int i,j,temp,min_index; for(j=0;p+j<q-1;j++) { min_index=j; for(i=j+1;p+i<q;i++) if(*(p+i)<*(p+min_index)) min_index=i; temp=*(p+min_index); *(p+min_index)=*(p+j); *(p+j)=temp; } } } void display(int *p,int *q) { for(;p<q;p++) printf("%d ",*p); }
No comments:
Post a Comment