I was reading about the elementary sorting algorithms like insertion Sort, selection sort and bubble Sort in Introduction to Algorithms by Cormen and I decided to try and implement it in C.
#include<stdio.h>
#define MAXSIZE 100 // Maximum number of elements permissible in array
void swap(int*,int*);
void print(int*,int);
int main(void) {
int arr[MAXSIZE],n,i,j,ch,ord;
void insertion(int*,int,int),selection(int*,int,int),bubble(int*,int,int);
printf("\nEnter number of elements for array = ");
scanf("%d",&n);
printf("\n\nEnter the array elements one by one : \n\n");
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
printf("\n\nWhat sorting you want to use ?\n\n Insertion (1) , Selection (2) or Bubble (3)\n\nEnter choice = ");
scanf("%d",&ch);
printf("\n\nSorting order ? \n\n Ascending (1) or Descending (2)\n\nEnter choice = ");
scanf("%d",&ord);
printf("\n\n");
switch(ch){
case 1:
insertion(arr,n,ord);
break;
case 2:
selection(arr,n,ord);
break;
case 3:
bubble(arr,n,ord);
}
print(arr,n);
printf("\n\n");
return 0;
}
void swap(int *x,int *y){
int t=*x;
*x=*y;
*y=t;
}
void insertion(int *a,int l,int ord){
int i,j;
for(i=1;i<l;i++){
for(j=i;j>0;j--){
if((ord==1 && a[j]<a[j-1]) || (ord==2 && a[j]>a[j-1]))
swap(&a[j],&a[j-1]);
else
break;
}
}
}
void selection(int *a,int l,int ord){
int index,i,j;
for(i=0;i<l;i++){
index=i;
for(j=i;j<l;j++){
if((ord==1 && a[j]<a[index]) || (ord==2 && a[j]>a[index]))
index=j;
}
swap(&a[i],&a[index]);
}
}
void bubble(int *a,int l,int ord){
int i,j;
for(i=l;i>0;i--){
for(j=0;j<i-1;j++){
if((ord==1 && a[j]>a[j+1]) || (ord==2 && a[j]<a[j+1]))
swap(&a[j],&a[j+1]);
}
}
}
void print(int *a,int l){
int i;
for(i=0;i<l;i++)
printf("%d\t",a[i]);
}
I'm looking for feedback / improvements on my code and whether the implementation of the sorting algorithms in the respective function definitions are proper or not.