Srting Algos
Srting Algos
Srting Algos
Assignment -4
Data Structure & Algorithms
Submitted by: M.Umer Farooq Roll no:77
Submitted to: Mam Unaiza Rehman Section: B
Class: BSCS Semester: 3rd
Question-1:
Write the code of the following sorting algorithms.
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Quick Sort
5. Merge Sort
Bubble Sort:
#include<iostream>
using namespace std;
int main(){
int array[10]={10,5,4,3,2,5,7,8,9,10};
int count=1;
while(count<10){
for(int i=0;i<10-count;i++){
if(array[i]<array[i+1]){
int temp=array[i+1];
array[i+1]=array[i];
array[i]=temp;
}
}
count++;
}
for(int i=0;i<10;i++){
cout<<array[i];
}
}
Selection Sort:
#include<iostream>
using namespace std;
int main(){
int array[5]={5,4,1,2,6};
for(int i=0;i<5;i++){
for(int j=i+1;j<4;j++){
if(array[j]<array[i]){
int temp=array[j];
array[j]=array[i];
array[i]=temp;
}
}
}
for(int i=0;i<5;i++){
cout<<array[i];
}
}
Insertion Sort:
#include<iostream>
using namespace std;
int main(){
int array[10]={10,5,4,3,2,5,7,8,9,10};
for(int i=1;i<10;i++){
int temp=array[i];
int j=i-1;
while(array[j]< temp&&j>=0){
array[j+1]=array[j];
j--;
}
array[j+1]=temp;
}
for(int i=0;i<10;i++){
cout<<array[i];
}
}
Quick Sort:
#include <iostream>
using namespace std;
int count = 0;
for (int i = start + 1; i <= end; i++) {
if (arr[i] <= pivot)
count++;
}
int pivotIndex = start + count;
swap(arr[pivotIndex], arr[start]);
int i = start, j = end;
return pivotIndex;
}
int main()
{
int arr[] = { 9, 3, 4, 2, 1, 8 };
int n = 6;
quickSort(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Merge Sort:
#include <iostream>
using namespace std;
void merge(int array[], int const left, int const mid,
int const right)
{
auto const subArrayOne = mid - left + 1;
auto const subArrayTwo = right - mid;
auto indexOfSubArrayOne
= 0; // Initial index of first sub-array
indexOfSubArrayTwo
= 0; // Initial index of second sub-array
int indexOfMergedArray
= left; // Initial index of merged array