I want to do insertion sort on a vector using vector::begin and vector::end. This is my code:
#include <iostream>
#include <vector>
using namespace std;
//Checking if vector is sorted
bool isSorted(vector<int>::iterator x, vector<int>::iterator y) {
for (vector<int>::iterator it = x; it != y; ++it) {
if (*x > *it) return false;
}
return true;
}
//Doing insertion sort algorithm
void insertionSort(vector<int>::iterator x, vector<int>::iterator y) {
while(!isSorted(x, y)) {
int smallest = *x;
int* pointer;
for (vector<int>::iterator it = x; it != y; ++it) {
if (*it < smallest) {
smallest = *it;
*pointer = *it;
}
}
int buffer = *x;
*x = smallest;
*pointer = buffer;
}
}
int main() {
vector<int> list;
list.push_back(5);
list.push_back(3);
list.push_back(4);
list.push_back(0);
list.push_back(10);
list.push_back(1);
//Displaying
for (int i = 0; i < list.size(); i++) {
cout << list[i] << endl;
}
insertionSort(list.begin(), list.end());
//Displaying after sort
cout << "\nafter sort" << endl;
for (int i = 0; i < list.size(); i++) {
cout << list[i] << endl;
}
}
And this is the output:
5
3
4
0
10
1
after sort
0
3
4
0
10
1
Expected output of after sort: 0,0,1,3,4,10. The insertion sort ain't working as expected. In the function insertionSort() I want to iterate until smallest element found, if found place that one on the first index in place.
I guess the problem is occurs somewhere on line 28, however I can't figure out what the problem is because the pointers etc make it somewhat complex.