Skip to content

Commit 4a24669

Browse files
committed
Add implementation for Insertion Sort Part 2 solution
This solution sorts an array iteratively using insertion sort and prints the array after each pass. It includes helper functions for input trimming and parsing to handle user input effectively. The implementation adheres to problem specifications with clear and concise code.
1 parent 6205ee4 commit 4a24669

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

Diff for: InsertionSortPart2.cpp

+100
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
string ltrim(const string &);
6+
string rtrim(const string &);
7+
vector<string> split(const string &);
8+
9+
/*
10+
* Complete the 'insertionSort2' function below.
11+
*
12+
* The function accepts following parameters:
13+
* 1. INTEGER n
14+
* 2. INTEGER_ARRAY arr
15+
*/
16+
17+
void insertionSort2(int n, vector<int> arr) {
18+
for (int i = 1; i < n; i++) {
19+
int key = arr[i]; // Current number to be inserted
20+
int j = i - 1;
21+
22+
// Move elements of arr[0..i-1], that are greater than key,
23+
// to one position ahead of their current position
24+
while (j >= 0 && arr[j] > key) {
25+
arr[j + 1] = arr[j];
26+
j--;
27+
}
28+
arr[j + 1] = key;
29+
30+
// Print the array after each pass
31+
for (int k = 0; k < n; k++) {
32+
cout << arr[k] << " ";
33+
}
34+
cout << endl;
35+
}
36+
}
37+
38+
int main()
39+
{
40+
string n_temp;
41+
getline(cin, n_temp);
42+
43+
int n = stoi(ltrim(rtrim(n_temp)));
44+
45+
string arr_temp_temp;
46+
getline(cin, arr_temp_temp);
47+
48+
vector<string> arr_temp = split(rtrim(arr_temp_temp));
49+
50+
vector<int> arr(n);
51+
52+
for (int i = 0; i < n; i++) {
53+
int arr_item = stoi(arr_temp[i]);
54+
55+
arr[i] = arr_item;
56+
}
57+
58+
insertionSort2(n, arr);
59+
60+
return 0;
61+
}
62+
63+
string ltrim(const string &str) {
64+
string s(str);
65+
66+
s.erase(
67+
s.begin(),
68+
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
69+
);
70+
71+
return s;
72+
}
73+
74+
string rtrim(const string &str) {
75+
string s(str);
76+
77+
s.erase(
78+
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
79+
s.end()
80+
);
81+
82+
return s;
83+
}
84+
85+
vector<string> split(const string &str) {
86+
vector<string> tokens;
87+
88+
string::size_type start = 0;
89+
string::size_type end = 0;
90+
91+
while ((end = str.find(" ", start)) != string::npos) {
92+
tokens.push_back(str.substr(start, end - start));
93+
94+
start = end + 1;
95+
}
96+
97+
tokens.push_back(str.substr(start));
98+
99+
return tokens;
100+
}

0 commit comments

Comments
 (0)