1
- // Insertion sort algorithm implemented in C++
2
-
3
1
#include < iostream>
2
+ #include < conio.h>
3
+ #include < stdlib.h>
4
+
5
+ #define MAX_SIZE 5
6
+
4
7
using namespace std ;
5
8
6
- // Insertion sort function
7
-
8
- void insertionSort (int array[],int size){
9
- int current;
10
- int i,j;
11
- for (i=0 ;i<size;i++){
12
- current=array[i];
13
- for (j=i;j>0 && array[j-1 ] > current;j--){
14
- array[j]=array[j-1 ];
15
- }
16
- array[j]=current;
17
- }
9
+ void insertion (int []);
10
+
11
+ int main () {
12
+ int arr_sort[MAX_SIZE], i;
13
+
14
+ cout << " Simple C++ Insertion Sort Example - Array and Functions\n " ;
15
+ cout << " \n Enter " << MAX_SIZE << " Elements for Sorting : " << endl;
16
+ for (i = 0 ; i < MAX_SIZE; i++)
17
+ cin >> arr_sort[i];
18
+
19
+ cout << " \n Your Data :" ;
20
+ for (i = 0 ; i < MAX_SIZE; i++) {
21
+ cout << " \t " << arr_sort[i];
22
+ }
23
+
24
+ insertion (arr_sort);
25
+ getch ();
18
26
}
19
27
20
- // Main function to perform sorting
21
-
22
- int main (){
23
- int i;
24
- int array_size;
25
- cout<< " Enter the size of the array to be sorted: " ;
26
- cin>> array_size;
27
- int array[array_size];
28
- cout<<" Enter the elements of the array to be sorted: " ;
29
- for (i=0 ;i<array_size;i++){
30
- cin>>array[i];
28
+ void insertion (int fn_arr[]) {
29
+ int i, j, a, t;
30
+ for (i = 1 ; i < MAX_SIZE; i++) {
31
+ t = fn_arr[i];
32
+ j = i - 1 ;
33
+
34
+ while (j >= 0 && fn_arr[j] > t) {
35
+ fn_arr[j + 1 ] = fn_arr[j];
36
+ j = j - 1 ;
37
+ }
38
+ fn_arr[j + 1 ] = t;
39
+
40
+ cout << " \n Iteration : " << i;
41
+ for (a = 0 ; a < MAX_SIZE; a++) {
42
+ cout << " \t " << fn_arr[a];
43
+ }
31
44
}
32
- insertionSort (array,array_size);
33
- cout<< " Sorted array is: \n " ;
34
- for (i= 0 ;i<array_size; i++){
35
- cout<<array[i]<< " \n " ;
45
+
46
+ cout << " \n\n Sorted Data : " ;
47
+ for (i = 0 ; i < MAX_SIZE; i++) {
48
+ cout << " \t " << fn_arr[i] ;
36
49
}
37
- return 0 ;
38
- }
50
+ }
0 commit comments