0% found this document useful (0 votes)
14 views5 pages

Q3

Uploaded by

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

Q3

Uploaded by

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

#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

int c = 0;

void bubbleSort(int arr[], int n){

for (int i = 0; i < n - 1; i++){

for (int j = 0; j < n - i - 1; j++){

c++;

if (arr[j] > arr[j + 1]){

swap(arr[j], arr[j + 1]);

void insertionSort(int arr[], int n) {

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

int key = arr[i];

int j = i - 1;

c++;

while (j >= 0 && arr[j] > key) {

c++;

arr[j + 1] = arr[j];

j--;

}
arr[j + 1] = key;

void selectionSort(int arr[], int n) {

for (int i = 0; i < n - 1; i++) {

int minIndex = i;

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

c++;

if (arr[j] < arr[minIndex]) {

minIndex = j;

swap(arr[i], arr[minIndex]);

void shellSort(int arr[], int n) {

for (int gap = n / 2; gap > 0; gap /= 2) {

for (int i = gap; i < n; i++) {

int temp = arr[i];

int j;

c++;

for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {

c++;

arr[j] = arr[j - gap];

arr[j] = temp;

}
}

void display(int arr[], int n) {

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

cout << arr[i] << " ";

cout << endl;

int main() {

srand(time(0));

int n = 20;

int arr[n];

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

arr[i] = rand() % 100 + 1;

cout << "Random Array: " << endl;

display(arr, n);

c = 0;

bubbleSort(arr, n);

cout << "\nBubble Sort: " << endl;

display(arr, n);

cout << "Comparisons: " << c << endl;

c = 0;
insertionSort(arr, n);

cout << "\nInsertion Sort: " << endl;

display(arr, n);

cout << "Comparisons: " << c << endl;

c = 0;

selectionSort(arr, n);

cout << "\nSelection Sort: " << endl;

display(arr, n);

cout << "Comparisons: " << c << endl;

c = 0;

shellSort(arr, n);

cout << "\nShell Sort: " << endl;

display(arr, n);

cout << "Comparisons: " << c << endl;

You might also like