Elementry Sorting Algorithm - LeetCode Discuss
Elementry Sorting Algorithm - LeetCode Discuss
New 10
Explore Problems Interview Contest Discuss Store Premium 387
#include <bits/stdc++.h>
using namespace std;
//Bubble Sort
void bubble(int arr[],int n){
//TC=O(n^2) , SC=O(1)
for(int i=n-1;i>=0;i--){
for(int j=0;j<=i-1;j++){
if(arr[j]>arr[j+1]){
swap(arr[j],arr[j+1]);
}
}
}
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
//Selection Sort
void selection(int arr[],int n){
//TC=O(n^2) , SC=O(1)
for(int i=0;i<n;i++){
int mini=i;
for(int j=i+1;j<n;j++){
if(arr[i]<arr[mini]){
mini=i;
}
}
swap(arr[i],arr[mini]);
}
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
//Insertion Sort
void insertion(int arr[],int n){
//TC=O(n^2) , SC=O(1)
for(int i=0;i<n;i++){
int j=i;
while(j>0 && arr[j-1]>arr[j]){
swap(arr[j-1],arr[j]);
j--;
}
}
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
//Quick Sort
int partiton(int arr[],int l,int r){
int pivo=arr[r];
i t i l 1
https://leetcode.com/discuss/study-guide/3237473/elementry-sorting-algorithm 1/1