0% found this document useful (0 votes)
9 views4 pages

Arrays Sorts

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views4 pages

Arrays Sorts

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

Bubble Sort

Selection Sort
Insertion Sort
Merge Sort
Quick Sort
Heap Sort
String Sorting

1)Selection Sort

dividing array into 2 parts : arr[i] and array after that


Then checking the min in other part and swapping it arr[i]
TC = O(n^2)
for(int i = 0 ; i!=(length-1);i++)
{
int min_pos=i;
for(int j = i+1 ; j<length ; j++)
{
if(arr[j]<a[min_pos])
min_pos=j;
}
if(min_pos!=i)
{
int temp = arr[i];
arr[i]=a[min_pos];
a[min_pos]=temp;
}
}

n-1 + n-2 + n-3 ..... + 1


=(n-1)(n)/2==> O(n^2)

2)Bubble sort

swapping the adjacent elements

int main() {
int n = 0 ;
cin >> n;
int arr[n];
for (int i = 0 ; i < n ; i++)
cin >> arr[i];
for (int i = 0 ; i < n ; i++)
{
for (int j = 0 ; j < n - 1 ; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
TC = n^2

//Optimizations : for(int j = 0 ; j< length -1 - i ; j++)


: using do while and removing outer i loop

bool swapped;
int i = 0 ;
do
{
swapped = false;
for (int j = 0 ; j < n - 1 ; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
i++;
}while(swapped);

3)**insertion sorting**

divide the array in 2 parts : left = unsorted and right = sorted


keep increasing the size of sorted array

for(int i = 1 ; i< n ; i++)


{
int key = arr[i];
int j = i-1;
while(j>=0 && arr[j]>key)
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=key;

i = 1 , j = 0
i = 2 , j = 1 , 0
.
.
.
.
i = n-1 , j = n-2 , n-3 ..... , 0

TC = O(n) or O(n^2)

4)QUICK SORT
#include<bits/stdc++.h>
#include<string>
#include<utility>
#include<cstdlib>
#include<ctime>

using namespace std;

void quicksort(int arr[], int n)


void quicksort_recursion(int arr[] , int low , int high);
int partition(int arr[],int low, int high);

int main()
{
cin >> n;
int arr[n];
for (int i = 0 ; i < n ; i++)
cin >> arr[i];
quicksort(arr,n);

for(int i = 0; i<n ; i++)


cout<<a[i]<<" ";

void quicksort(int arr[],int n )


{
quicksort_recursion(arr,0,n-1);
}

void quicksort_recursion(int arr[] , int low , int high)


{
if(low<high)
{
int pivot_index = partition(arr, low , high);
quicksort_recursion(array , low , pivot_index-1);
quicksort_recursion(array , pivot_index_index+1 , high);
}
}

int partition(int arr[] , int low , int high)


{
int pivot_value = array[high];
int i = low;

for(int j = low ; j < high ; j++)


{
if(array[j]<= pivot_value)
{
swap(array[i],array[j]);
i++;
}
}

swap(array[i], array[high]);
return i ;
}

You might also like