Elementry Sorting Algorithm - LeetCode Discuss

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

3/23/23, 10:56 PM (10) Elementry Sorting Algorithm - LeetCode Discuss

New 10
Explore Problems Interview Contest Discuss Store Premium 387

Back Elementry Sorting Algorithm

R_aghav 73 Last Edit: March 15, 2023 3:46 PM 54 VIEWS S


h
a
2 Time complexity of first three Algorithm are same that is O(N^2) and Space Complexity will be O(1) r
e

#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

You might also like