Skip to content

Commit b989bb2

Browse files
committed
Added selection and insertion sort programs in c++
1 parent 4b20678 commit b989bb2

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

C++/InsertionSort.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include<iostream>
2+
using namespace std;
3+
void display(int *array, int n) {
4+
for(int i = 0; i<n; i++)
5+
cout << array[i] << " ";
6+
cout << endl;
7+
}
8+
void insertionSort(int *array, int n) {
9+
int key, j;
10+
for(int i = 1; i<n; i++) {
11+
key = array[i];//take value
12+
j = i;
13+
while(j > 0 && array[j-1]>key) {
14+
array[j] = array[j-1];
15+
j--;
16+
}
17+
array[j] = key; //insert in right place
18+
}
19+
}
20+
int main() {
21+
int n;
22+
cout << "Enter the number of elements: ";
23+
cin >> n;
24+
int arr[n]; //create an array with given number of elements
25+
cout << "Enter elements:" << endl;
26+
for(int i = 0; i<n; i++) {
27+
cin >> arr[i];
28+
}
29+
cout << "Array before Sorting: ";
30+
display(arr, n);
31+
insertionSort(arr, n);
32+
cout << "Array after Sorting: ";
33+
display(arr, n);
34+
}

C++/SelctionSort.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include<iostream>
2+
using namespace std;
3+
void swapping(int &a, int &b) { //swap the content of a and b
4+
int temp;
5+
temp = a;
6+
a = b;
7+
b = temp;
8+
}
9+
void display(int *array, int n) {
10+
for(int i = 0; i<n; i++)
11+
cout << array[i] << " ";
12+
cout << endl;
13+
}
14+
void selectionSort(int *array, int n) {
15+
int i, j, imin;
16+
for(i = 0; i<n-1; i++) {
17+
imin = i; //get index of minimum data
18+
for(j = i+1; j<n; j++)
19+
if(array[j] < array[imin])
20+
imin = j;
21+
//placing in correct position
22+
swap(array[i], array[imin]);
23+
}
24+
}
25+
int main() {
26+
int n;
27+
cout << "Enter the number of elements: ";
28+
cin >> n;
29+
int arr[n]; //create an array with given number of elements
30+
cout << "Enter elements:" << endl;
31+
for(int i = 0; i<n; i++) {
32+
cin >> arr[i];
33+
}
34+
35+
selectionSort(arr, n);
36+
cout << "Array after Sorting: ";
37+
display(arr, n);
38+
}

0 commit comments

Comments
 (0)