Arjun Suresh (talk | contribs) |
Arjun Suresh (talk | contribs) |
||
Line 1: | Line 1: | ||
− | + | [[https://armi.in/wiki/Complexity_of_Basic_Sorting_Algorithms |Complexity and no. of swaps required]] | |
− | |||
− | |||
<syntaxhighlight lang="c"> | <syntaxhighlight lang="c"> | ||
Line 66: | Line 64: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |||
+ | |||
{{Template:FBD}} | {{Template:FBD}} | ||
[[Category: Code]] | [[Category: Code]] |
[|Complexity and no. of swaps required]
<syntaxhighlight lang="c">
void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
void qsort(int a[], int start, int end) { int i, j, p; if(start >= end-1) { return; } i = p = start, j = end-1; while(i < j) { while(a[i] <= a[p] && i < end-1) i++; while(a[j] > a[p]) j--; if(i < j) { swap(&a[i], &a[j]); } } swap(&a[j], &a[p]); qsort(a, start, j); qsort(a, j + 1, end); }
void printArray(int a[], int n) { int i; for(i = 0; i < n; i++) { printf("%d ",a[i]); } }
int main() { char str[20]; int num[100]; int i = 0; printf("Enter the numbers to sort (. to stop): "); while(1) { scanf("%s",str); if(str[0] == '.') break; sscanf(str, "%d", &num[i++]); } qsort(num, 0, i); printf("The sorted numbers are: "); printArray(num, i); printf("\n"); } </syntaxhighlight>
Complexity <math>\theta(n)</math>
No. of swaps in the worst case = <math> \lfloor n/2 \rfloor</math>
<syntaxhighlight lang="c">
void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
void qsort(int a[], int start, int end) { int i, j, p; if(start >= end-1) { return; } i = p = start, j = end-1; while(i < j) { while(a[i] <= a[p] && i < end-1) i++; while(a[j] > a[p]) j--; if(i < j) { swap(&a[i], &a[j]); } } swap(&a[j], &a[p]); qsort(a, start, j); qsort(a, j + 1, end); }
void printArray(int a[], int n) { int i; for(i = 0; i < n; i++) { printf("%d ",a[i]); } }
int main() { char str[20]; int num[100]; int i = 0; printf("Enter the numbers to sort (. to stop): "); while(1) { scanf("%s",str); if(str[0] == '.') break; sscanf(str, "%d", &num[i++]); } qsort(num, 0, i); printf("The sorted numbers are: "); printArray(num, i); printf("\n"); } </syntaxhighlight>