#include<stdio.h> #include<stdlib.h> void InsertSort(int arr[],int length); void ShellSort(int arr[],int length); void SelectSort(int arr[],int length); void BubbleSort(int arr[],int length); void QuickSort(int arr[],int low,int high); void MergeSort(int arr[],int low,int high); void Merge(int arr[],int low,int mid,int high); int Partition(int arr[],int low,int high); int main() { int i=0; int j=0; int k=0; int n=9; int A[]={ 0,5,9,1,4,11,80,3,10 }; for(i=0;i<n;i++){ printf("%d ",A[i]); } printf(" "); BubbleSort(A,9); // SelectSort(A,9); // QuickSort(A,1,8); // ShellSort(A,8); // InsertSort(A,8); // MergeSort(A,1,8); for(k=0;k<n;k++) { printf("%d ",A[k]); } return 0; } void InsertSort(int arr[],int length) { int i=0; int j=0; for(i=2;i<=length;i++) { if(arr[i]<arr[i-1]) { arr[0]=arr[i]; for(j=i-1;arr[0]<arr[j];j--) { arr[j+1]=arr[j]; } arr[j+1]=arr[0]; } } } void ShellSort(int arr[],int length) { int dk=length/2; int i=0; int j=0; for(;dk>=1;dk=dk/2) { for(i=dk+1;i<=length;i++) { if(arr[i]<arr[i-dk]) { arr[0]=arr[i]; //arr[0] temporary storage unit. for(j=i-dk;j>0&&arr[0]<arr[j];j-=dk) { arr[j+dk]=arr[j]; } arr[j+dk]=arr[0]; } } for(int k=0;k<=length;k++) { printf("%d ",arr[k]); } printf(" "); } } void SelectSort(int arr[],int length) { int i=0; int j=0; int min=0; int temp=0; for(int i=1;i<length-1;i++) { min=i; for(j=i+1;j<length;j++) { if(arr[j]<arr[min]) { min=j; } } if(min!=i) { temp=arr[i]; arr[i]=arr[min]; arr[min]=temp; } for(int k=0;k<length;k++) { printf("%d ",arr[k]); } printf(" "); } } void QuickSort(int arr[],int low,int high) { if(low<high) { int pivotpos=Partition(arr,low,high); QuickSort(arr,low,pivotpos-1); QuickSort(arr,pivotpos+1,high); } } int Partition(int arr[],int low,int high) { int pivot=arr[low]; while(low<high) { while(low<high&&arr[high]>=pivot)--high; arr[low]=arr[high]; while(low<high&&arr[low]<=pivot)++low; arr[high]=arr[low]; } arr[low]=pivot; return low; } void Merge(int arr[],int low,int mid,int high) { int k=0; int i=0; int j=0; int len=high-low+2; int arr_temp[len]; // int *arr_temp=(int*)malloc((high-low)*sizeof(int)); for(k=low;k<=high;k++) { arr_temp[k]=arr[k]; } for(k=low;k<=high;k++) { printf("%d ",arr_temp[k]); } printf(" "); for(i=low,j=mid+1,k=i;i<=mid&&j<=high;k++) { if(arr_temp[i]<=arr_temp[j]) { arr[k]=arr_temp[i++]; } else { arr[k]=arr_temp[j++]; } } while(i<=mid)arr[k++]=arr_temp[i++]; while(j<=high)arr[k++]=arr_temp[j++]; for(k=low;k<=high;k++) { printf("%d ",arr[k]); } printf(" "); } void MergeSort(int arr[],int low,int high) { if(low<high) { int mid=(low+high)/2; MergeSort(arr,low,mid); MergeSort(arr,mid+1,high); Merge(arr,low,mid,high); } } void BubbleSort(int arr[],int length) { int i=0; int j=0; int k=0; int temp=0; for(i=0;i<length-1;i++) { for(j=0;j<length-1-i;j++) { if(arr[j]>arr[j+1]) { temp=arr[j+1]; arr[j+1]=arr[j]; arr[j]=temp; } } for(k=0;k<length;k++) { printf("%d ",arr[k]); } printf(" "); } }