Sorting is the rearrangement of elements in into a specific order. Sorting algorithms helps in making the solution easier and efficient. Some basic yet important sort algorithms, that one must know are as follows:
void selection_sort(vector <int> arr, int n){
int min_index=i;
for(int j=i;j<n;j++){
if(arr[j]<arr[min_index])
min_index=j;
}
swap(arr[i],arr[min_index]);
}
void bubble_sort(vector <int> arr, int n){
for(int itr=1;itr<n;itr++){
for(int j=0;j<(n-itr-);j++){
if(arr[j]>arr[j+1])
swap(arr[j],arr[j+1]);
}
}
}
Recursive Bubble Sort:
void bubble_sort(vector <int> arr, int n){
if (n == 1) // Base case
return;
for (int i=0; i<n-1; i++)
if (arr[i] > arr[i+1])
swap(arr[i], arr[i+1]);
bubble_sort(arr, n-1);
}
void insertion_sort(vector <int> arr, int n){
for(int i=1;j<n;j++){
int e=arr[i];
int j=i-1;
while(j>=0 && arr[j]<arr[j]>e){
a[j+1]=a[j];
j=j-1;
}
a[j+1]=e;
}