Skip to content

Instantly share code, notes, and snippets.

@raunaqbn
Last active August 15, 2016 21:46
Show Gist options
  • Save raunaqbn/d4c16a6db7e984e5040cea59187c556b to your computer and use it in GitHub Desktop.
Save raunaqbn/d4c16a6db7e984e5040cea59187c556b to your computer and use it in GitHub Desktop.
Arrays
/*Program which takes an input array and an index and rearranges the array such that values less than the element come first,
elements equal follow and finally followed by elements greater than the index element*/
//Notes: This is just the quicksort algorithm where they have given the random value and there is just one step
This solution is the same as the precvious code: only just add a condition to increment the current index when the values match
/*To work with arrays in place we need to keep 2 pointers: first where the last evenm element was inserted and the next where
the last odd element was inserted. We can use a vector for the array here.*/
#include <vector>
void swap(int &a,int &b)
{
int temp = a;
a = b;
b = temp;
}
void sortEvenOdd(vector<int>* array)
{
int evenIndex = 0,currentIndex = 0;
int oddIndex = array.size()-1;
while (currentIndex < oddIndex)
{
if (array[currenIndex] % 2 == 0)
{
swap(array[currentIndex],array[evenIndex]);
evenIndex++;
}
else
{
swap(array[currentIndex],array[oddIndex]);
oddIndex++;
}
currentIndex++;
}
}
//Notes: CurrentIndex is not really needed. You can just use the even index!
/*Program to take an array representing a decimal and adding 1 to it
eg. <1,2,9> will give result <1,3,0>
*/
vector<int> AddOne(vector<int> A)
{
++A.back();
for (int i = A.size() -1; A[i] == 10 && i > 1; i++)
{
A[i] = 0;
++A [i-1];
}
if (A[0] == 10)
{
A[0] = 0;
A.insert(A.begin(),1);
}
return A;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment