Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- void swap(int *,int *);
- void cs_sort(int *,int);
- void bubblesort(int* ,int);
- void quicksort(int *,int,int);
- int partition(int *,int,int);
- int main()
- {
- int n,u,l,i,input;
- clock_t start,end;
- double total;
- printf("Enter number of elements:");
- scanf("%d",&n);
- printf("Enter range for generating numbers(lower bound-upper bound):");
- scanf("%d %d",&l,&u);
- int *array=(int *)malloc(sizeof(int)*n);
- srand((unsigned)time(NULL));
- for(i=0;i<n;i++)
- array[i]=l+rand()%(u-l);
- /*printf("Before sorting:\n");
- for(i=0;i<n;i++)
- printf("%d,",array[i]);*/
- printf("Enter your preference:\n1:bubblesort\n2:cocktail shaker sort\n3:quicksort\n");
- scanf("%d",&input);
- start=clock();
- switch(input){
- case 1:bubblesort(array,n);break;
- case 2:cs_sort(array,n);break;
- case 3:quicksort(array,0,n-1);break;
- default:printf("Wrong input");break;
- }
- end=clock();
- printf("Sorted array:\n");
- for(i=0;i<n;i++)
- printf("%d,",array[i]);
- total=(double)(end-start)/CLOCKS_PER_SEC;
- printf("\n\nTime taken: %lf seconds\n",total);
- return 0;
- }
- void swap(int *a,int *b){
- int temp;
- temp=*a;
- *a=*b;
- *b=temp;
- }
- void bubblesort(int *a,int n){
- int i,j;
- for (i=0;i<n-1;i++)
- for (j=0;j<n-i-1;j++){
- if (a[j]>a[j+1])
- swap(a+j,a+j+1);
- }
- }
- void cs_sort(int *a,int n){
- int i,swapped=1,start,end;
- start=0;
- end=n-1;
- while(swapped){
- swapped=0;
- for(i=start;i<end;i++){
- if(a[i]>a[i+1]){
- swap(a+i,a+i+1);
- swapped++;
- }
- }
- if(!swapped)
- break;
- end--;
- for(i=end;i>=start;i--){
- if(a[i]>a[i+1]){
- swap(a+i,a+i+1);
- swapped++;
- }
- }
- start++;
- }
- }
- void quicksort(int *a,int l,int r){
- if(l<r){
- int q=partition(a,l,r);
- quicksort(a,l,q-1);
- quicksort(a,q+1,r);
- }
- }
- int partition(int *a,int l,int r){
- int x=a[l];
- int i=l+1,j;
- for(j=l+1;j<=r;j++){
- if(a[j]<x){
- swap(a+i,a+j);
- i++;
- }
- }
- swap(a+l,a+i-1);
- return i-1;
- }
Add Comment
Please, Sign In to add comment