forked from argonautica/sorting-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added selection and insertion sort programs in c++
- Loading branch information
1 parent
4b20678
commit b989bb2
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |