Skip to content

Instantly share code, notes, and snippets.

@suubh
Created December 8, 2021 09:44
Show Gist options
  • Save suubh/0b521f00faaa4c608c5ac445ab01b1d2 to your computer and use it in GitHub Desktop.
Save suubh/0b521f00faaa4c608c5ac445ab01b1d2 to your computer and use it in GitHub Desktop.
Sorting Algorithms
//--------------------------- SELECTION SORT ---------------------------//
#include<iostream>
using namespace std;
void selection(int arr[], int n){
// First objective is to find the INDEX of the min element
for(int i=0;i<n-1;i++){
int min_ele_index = i;
for(int j = i+1;j<n;j++){
if(arr[j] < arr[min_ele_index]){
min_ele_index = j;
}
}
// Now swap the min element with the first index of the array
int temp = arr[i];
arr[i] = arr[min_ele_index];
arr[min_ele_index] = temp;
}
}
int main(){
int arr[] = {4,1,3,2};
int n = 4;
selection(arr, n);
for(int i=0;i<n;i++){
cout << arr[i] << " ";
}
return 0;
}
//-----------------------------------------------------------------------//
//----------------------------- BUBBLE SORT -----------------------------//
#include<iostream>
using namespace std;
void bubble(int arr[], int n){
for(int i=0;i<n;i++){
for (int j=i+1;j<n;j++){
if (arr[j]<arr[i]){
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
int main(){
int arr[] = {4,1,3,2};
int n = 4;
bubble(arr, n);
for(int i=0;i<n;i++){
cout << arr[i] << " ";
}
return 0;
}
//-----------------------------------------------------------------------//
//---------------------------- INSERTION SORT ---------------------------//
//-----------------------------------------------------------------------//
//------------------------------ MERGE SORT -----------------------------//
//-----------------------------------------------------------------------//
//------------------------------ QUICK SORT -----------------------------//
//-----------------------------------------------------------------------//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment