Last active
August 29, 2015 14:06
-
-
Save tristaaan/7499f64855028c220476 to your computer and use it in GitHub Desktop.
Create a sorted array by inserting the elements in a sorted manner.
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
void sortedInsert(vector<double> &v, double val){ | |
if (v.size() == 0){ | |
v.push_back(val); | |
return; | |
} | |
vector<double>::iterator start = v.begin(); | |
vector<double>::iterator end = v.end(); | |
while (true){ | |
end -= 1; | |
vector<double>::iterator middle = v.begin(); | |
double vBegin = start - v.begin(); | |
double diff = end - start; | |
advance(middle, ceil(diff/2)+vBegin); //ceil((end-start)/2) + start; | |
if (*end <= *start){ | |
if (val >= *end){ | |
v.insert(end+1, val); | |
//cout << "end e<=s" << endl; | |
break; | |
} | |
else{ | |
v.insert(start, val); | |
//cout << "beginning e<=s" << endl; | |
break; | |
} | |
} | |
else if (val <= *start){ | |
v.insert(start, val); | |
//cout << "beginning" << endl; | |
break; | |
} | |
else if (val >= *end){ | |
v.insert(end+1, val); | |
//cout << "end" << endl; | |
break; | |
} | |
else if (val < *middle){ | |
end = middle; | |
} | |
else if (val >= *middle){ | |
start = middle; | |
} | |
} | |
} |
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
def sortedInsert(val): | |
if len(A) == 0: | |
A.append(val) | |
return | |
start = 0 | |
end = len(A) | |
while True: | |
end-=1 | |
middle = int(math.ceil((end-start)/2)) + start | |
if end <= start: | |
if val >= A[end]: | |
A.insert(end+1, val) | |
break | |
else: | |
A.insert(start, val) | |
break | |
elif val <= A[start]: | |
A.insert(start, val) | |
break | |
elif val >= A[end]: | |
A.insert(end+1, val) | |
break | |
elif val < A[middle]: | |
end = middle | |
elif val >= A[middle]: | |
start = middle |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment