Skip to content

Instantly share code, notes, and snippets.

@tristaaan tristaaan/SortedInsert.cpp
Last active Aug 29, 2015

Embed
What would you like to do?
Create a sorted array by inserting the elements in a sorted manner.
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;
}
}
}
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
You can’t perform that action at this time.