1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
int binSearch(vector<int> vec, int number, int smallest, int largest)
{
int vec_ptr = ((largest - smallest) / 2) + smallest;
if (number == vec[vec_ptr])
return vec_ptr;
if (number > vec[vec_ptr])
{
if (smallest == vec_ptr && largest == (vec_ptr + 1))
return largest;
smallest = vec_ptr;
return binSearch(vec, number, smallest, largest);
}
if (number < vec[vec_ptr])
{
if (smallest == vec_ptr && largest == (vec_ptr + 1))
return smallest;
largest = vec_ptr;
return binSearch(vec, number, smallest, largest);
}
}
vector<int> pushOnIndex(vector<int> vec, int index, int number)
{
vector<int> cpy_vec;
for (int i = 0; i < index; i++)
cpy_vec.push_back(vec[i]);
cpy_vec.push_back(number);
for (int i = index; i < vec.size(); i++)
cpy_vec.push_back(vec[i]);
return cpy_vec;
}
vector<int> sortVec(vector<int> vec){
vector<int> sorted_vec;
sorted_vec.push_back(vec[0]);
for (int i = 1; i < vec.size(); i++)
{
if (vec[i] > sorted_vec[sorted_vec.size() - 1])
{
sorted_vec.push_back(vec[i]);
continue;
}
if (vec[i] < sorted_vec[0])
{
sorted_vec = pushOnIndex(sorted_vec, 0, vec[i]);
continue;
}
int pos = binSearch(sorted_vec, vec[i], 0, sorted_vec.size() - 1);
sorted_vec = pushOnIndex(sorted_vec, pos, vec[i]);
}
return sorted_vec;
}
int main()
{
vector<int> nums = {66, 190, 45, -123, -445, 990, -1, 0, 30001, -999, 22, 23, 25, 1, 12, 32, 52, 72};
vector<int> sorted_vec = sortVec(nums);
}
|