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

1.

Code for Selection sort:-

#include <iostream>

using namespace std;

int count = 0;

void swapping(int &a, int &b)

//swap the content of a and b

int temp;

temp = a;

a = b;

b = temp;

void display(int *array, int size)

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

cout << array[i] << " ";

cout << endl;

void selectionSort(int *array, int size)

int i, j, imin;

for(i = 0; i<size-1; i++)

imin = i; //get index of minimum data


for(j = i+1; j<size; j++)

if(array[j] < array[imin])

imin = j;

count++; //count the Number of swaps

//placing in correct position

swap(array[i], array[imin]);

int main()

int arr[10] = {0};

cout << "Enter elements:" << endl;

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

cin >> arr[i];

cout << "Array before Sorting: ";

display(arr, 10);

selectionSort(arr, 10);

cout << "Array after Sorting: ";

display(arr, 10);

//print the Number of swaps

cout<<"Number of times the data have been swapped: "<<count;

return 0;

Output:-
2
Code for bubble sort:-

#include <iostream>

using namespace std;

int count = 0;

void swapping(int &a, int &b)

//swap the content of a and b

int temp;

temp = a;

a = b;

b = temp;

void display(int *array, int size)

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

cout << array[i] << " ";

cout << endl;

}
void bubbleSort(int *array, int size)

int i, j;

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

for (j = 0; j < size-i-1; j++)

//compare the elements

if (array[j] > array[j+1])

//swap the elements so that heavy element is bring to end

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

count++;

int main()

int arr[10] = {0};

cout << "Enter elements:"<<endl;

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

cin >> arr[i];

cout << "Array before Sorting: ";

display(arr, 10);

bubbleSort(arr, 10);

cout << "Array after Sorting: ";

display(arr, 10);

//print the Number of swaps


cout<<"Number of times the data have been swapped: "<<count;

return 0;

Output:-

You might also like