Inserting Sort, Shell Sort, Heap Sort and Quick Sort
This passage contains the application of four Sorting Algorithms in the title Inserting Sort, Shell Sort, Heap Sort and Quick Sort . Sorting algorithms are fundamental in Computer Science and these four algorithms are basic for new hand.
Code
Below is the C code
#include<stdio.h>
#include<stdlib.h>
void InsertingSort(int A[], int N);
void ShellSort(int A[], int N);
void Swap(int A[] ,int a, int b);
void PrecDown(int A[], int i, int N);
void HeapSort(int A[], int N);
int Median3(int A[], int left, int right);
void Qsort(int A[], int left, int right);
void QuickSort(int A[], int N);
int main(){
int size;
scanf("%d", &size);
int* A = (int*)malloc(sizeof(int)*size);
for(int i=0; i<size;i++){
scanf("%d", &A[i]);
}
InsertingSort(A, size);
ShellSort(A, size);
HeapSort(A, size);
QuickSort(A, size);
for(int i=0; i<size; i++){
printf("%d ", A[i]);
}
}
void InsertingSort(int A[], int N){
int Tmp;
int P, j;
for(P=1; P<N; P++){
Tmp = A[P];
for(j=P; j>0&&A[j-1]>Tmp; j--){
//important 1.cmpare with Tmp; start just from P
//remember j is the place to fit in
A[j] = A[j-1];
}
A[j] = Tmp;
}
}
void ShellSort(int A[], int N){
int Tmp;
int P, j;
int Increment = N/2;
for(; Increment>0; Increment/=2){
//stop after Increment become 1
for(P=Increment; P<N; P++){
Tmp = A[P];
for(j=P; j>=Increment&&A[j-Increment]>Tmp; j-=Increment){
A[j] = A[j-Increment];
}
A[j] = Tmp;
}
}
}
void Swap(int A[] ,int a, int b){
int Tmp = A[a];
A[a] = A[b];
A[b] = Tmp;
return;
}
void PrecDown(int A[], int i, int N){
//be careful that generally when we apply a heap, we start from 1 instead of 0
int Tmp = A[i];
int child;
child = 2*i+1;
for(; child<N; child = 2*i+1){
//notice that left child is not naively i*2
if(child!=N-1&&A[child+1]>A[child])
child++;
if(A[child]>Tmp){
A[i] = A[child];
i = child;
}
else
break;
}
A[i] = Tmp;
}
void HeapSort(int A[], int N){
//pay attention that it's a Max heap
for(int i = N/2-1; i>=0; i--){
PrecDown(A, i, N);
}
int size = N;
//intitializing the heap
for(int i=0; i<size; i++){
Swap(A, 0, N-1);
PrecDown(A, 0, N-1);
N--;
}
return;
}
int Median3(int A[], int left, int right){
int mid = (left+right)/2;
if(A[left]>A[mid])
Swap(A, left, mid);
if(A[left]>A[right])
Swap(A, left, right);
if(A[mid]>A[right])
Swap(A, mid, right);
Swap(A, mid, right-1);
//the right item > mid, so hide mid just bufore right, instead of at right
return A[right-1];
//simple while complex
}
void Qsort(int A[], int left, int right){
//Not as easy as first sight
if(right - left >10){
int mid = Median3(A, left, right);
int i=left;
int j = right-1;
for(;;){
while(A[++i]<mid);
//actually i start from left+1, because after running Median3 the item at left must<mid
while(A[--j]>mid);
//j start from right-2
if(i>j)
break;
Swap(A, i, j);
}
Swap(A, i, right-1);
Qsort(A, left, i-1);
Qsort(A, i+1, right);
}
else
InsertingSort(A+left, right-left+1);
}
void QuickSort(int A[], int N){
Qsort(A, 0, N-1);
}