Last active
October 28, 2016 06:27
-
-
Save Highstaker/022ddf2b06919c92f8559a659881aeb0 to your computer and use it in GitHub Desktop.
Sorting algorithms in different languages
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
#include <stdio.h> | |
#include <time.h> | |
#include <stdlib.h> | |
#define ARR_LEN 100 | |
void swap(int *a, int *b) | |
{ | |
int temp = *a; | |
*a = *b; | |
*b = temp; | |
} | |
void bubblesort(int *arr, int len){ | |
int top = len-1; | |
int j, newtop; | |
while(top > 0){ | |
newtop = 0; | |
for(j=0;j<top;j++){ | |
if(arr[j] > arr[j+1]){ | |
swap(&arr[j], &arr[j+1]); | |
newtop = j+1; | |
} | |
} | |
top = newtop; | |
} | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
// const int len = 8; | |
// int arr[] = {8,1,5,6,3,4,2,7}; | |
int arr[ARR_LEN]; | |
int i; | |
srand(time(NULL)); | |
for(i=0;i<ARR_LEN;i++) | |
arr[i] = rand()%100; | |
for(i=0;i<ARR_LEN;i++) | |
printf("%d ", arr[i]); | |
printf("\n"); | |
bubblesort(arr, ARR_LEN); | |
for(i=0;i<ARR_LEN;i++) | |
printf("%d ", arr[i]); | |
printf("\n"); | |
return 0; | |
} |
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
#include<stdio.h> | |
#include<stdlib.h> | |
void swap(int *a, int *b) | |
{ | |
// *a = *a ^ *b; | |
// *b = *a ^ *b; | |
// *a = *a ^ *b; | |
int temp = *a; | |
*a = *b; | |
*b = temp; | |
} | |
void quicksort(int *arr, int start, int end) | |
{ | |
if(end-start<=0) | |
{ | |
return; | |
} | |
int P = start; | |
int L = start+1; | |
int R = end; | |
while(L <= R) | |
{ | |
while(arr[L] < arr[P] && L <= end) //a bug? L<=end should be BEFORE element comparison? | |
{ | |
L++; | |
} | |
if(arr[R] >= arr[P]) | |
{ | |
R--; | |
} | |
else | |
{ | |
if(L<=R) | |
{ | |
swap(&arr[L],&arr[R]); | |
} | |
} | |
} | |
//jumpover happened, swapping R and P and dividing | |
swap(&arr[R],&arr[P]); | |
quicksort(arr,start,R-1); | |
quicksort(arr,R+1,end); | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
int n, i; | |
int *arr; | |
printf("%s\n", "Array size: "); | |
scanf("%d", &n); | |
arr = malloc(n * sizeof(int)); | |
printf("Enter the elements to be sorted\n"); | |
for(i = 0; i < n; i++) | |
scanf("%d", &arr[i]); | |
quicksort(arr, 0, n-1); | |
for(i=0;i<n;i++) | |
printf("%d,", arr[i]); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment