Skip to content

Commit

Permalink
Added selection and insertion sort programs in c++
Browse files Browse the repository at this point in the history
  • Loading branch information
lakshyajit165 committed Oct 13, 2019
1 parent 4b20678 commit b989bb2
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
34 changes: 34 additions & 0 deletions C++/InsertionSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include<iostream>
using namespace std;
void display(int *array, int n) {
for(int i = 0; i<n; i++)
cout << array[i] << " ";
cout << endl;
}
void insertionSort(int *array, int n) {
int key, j;
for(int i = 1; i<n; i++) {
key = array[i];//take value
j = i;
while(j > 0 && array[j-1]>key) {
array[j] = array[j-1];
j--;
}
array[j] = key; //insert in right place
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
insertionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
38 changes: 38 additions & 0 deletions C++/SelctionSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include<iostream>
using namespace std;
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 n) {
for(int i = 0; i<n; i++)
cout << array[i] << " ";
cout << endl;
}
void selectionSort(int *array, int n) {
int i, j, imin;
for(i = 0; i<n-1; i++) {
imin = i; //get index of minimum data
for(j = i+1; j<n; j++)
if(array[j] < array[imin])
imin = j;
//placing in correct position
swap(array[i], array[imin]);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}

selectionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}

0 comments on commit b989bb2

Please sign in to comment.