Last active
August 29, 2015 14:25
-
-
Save pyk/03d859f81f5907e3369f to your computer and use it in GitHub Desktop.
Implementation of Sorting algotithm in C language
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* compile: gcc -o insertion-sort insertion-sort.c */ | |
#include <stdio.h> | |
int | |
main() | |
{ | |
int i; | |
int A[6] = {5, 2, 4, 6, 1, 3}; | |
for(i = 1; i < 6; i++) { | |
int key, j; | |
key = A[i]; | |
j = i - 1; | |
while(j >= 0 && A[j] > key) { | |
A[j+1] = A[j]; | |
j -= 1; | |
} | |
A[j+1] = key; | |
} | |
for(i = 0; i < 6; i++) | |
printf("%d ", A[i]); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* compile: gcc -o merge-sort merge-sort.c */ | |
#include <stdio.h> | |
#include <limits.h> | |
void merge(int A[], int p, int q, int r); | |
void merge_sort(int A[], int p, int r); | |
int | |
main() | |
{ | |
int i; | |
int A[10] = {4, 5, 66, 7, 33, 1, 33, 5, 8, 90}; | |
merge_sort(A, 0, 10); | |
for(i = 0; i < 10; i++) | |
printf("%d ", A[i]); | |
} | |
void | |
merge(int A[], int p, int q, int r) | |
{ | |
int i, j, k, nl, nr; | |
nl = q - p + 1; | |
nr = r - q; | |
int L[nl+1], R[nr+1]; | |
for(i = 0; i <= nl; i++) | |
L[i] = A[p + i - 1]; | |
for(j = 0; j <= nr; j++) | |
R[j] = A[q + j]; | |
L[nl + 1] = INT_MAX; | |
R[nr + 1] = INT_MAX; | |
i = j = 1; | |
for(k = p; k <= r; k++) { | |
if(L[i] <= R[j]) { | |
A[k] = L[i]; | |
i += 1; | |
} else { | |
A[k] = R[j]; | |
j += 1; | |
} | |
} | |
} | |
void | |
merge_sort(int A[], int p, int r) | |
{ | |
int q; | |
if(p < r) { | |
q = (p+r)/2; | |
merge_sort(A, p, q); | |
merge_sort(A, q+1, r); | |
merge(A, p, q, r); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* compile: gcc -o selection-sort selection-sort.c */ | |
#include <stdio.h> | |
int | |
main() | |
{ | |
int i; | |
int A[5] = {30, 3, 40, 100, 5}; | |
for(i = 0; i < 5; i++) { | |
int j, smallest, temp; | |
smallest = A[i]; | |
for(j = i; j < 5; j++) { | |
temp = smallest; | |
if(A[j] < smallest) { | |
smallest = A[j]; | |
A[j] = temp; | |
} | |
} | |
A[i] = smallest; | |
} | |
for(i = 0; i < 5; i++) | |
printf("%d ", A[i]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment