Skip to content

Instantly share code, notes, and snippets.

Created December 13, 2012 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/dd9417bfce828da75f36 to your computer and use it in GitHub Desktop.
Save anonymous/dd9417bfce828da75f36 to your computer and use it in GitHub Desktop.
my median method and main
import java.util.ArrayList;
import java.util.Random;
public class quicksortagain {
public static void main(String[] args) throws Exception
{
ArrayList<Integer> rList = new ArrayList<Integer>();
Random r = new Random();
for (int i = 0; i < 25; i++) rList.add(r.nextInt(50));
System.out.println(qkSort(rList, rList.size()/2));
}
/**
*
* @param intList
* @param k
* @return
* @throws Exception
*/
public static int qkSort(ArrayList<Integer> intList, int k) throws Exception
{
if(intList.size() == 1) return intList.get(0);
Random r = new Random();
int size = intList.size();
//System.out.println(size);
int randInt = r.nextInt(size);//pick a random int that is within the size of the list
int otherH = intList.get(randInt);//hold it for later use
intList.remove(randInt);//take out of list
ArrayList<Integer> lower = new ArrayList<Integer>();//place to store ints that are lower
ArrayList<Integer> higher = new ArrayList<Integer>();//place to store ints that are higher
for (int i = 0; i < intList.size(); i++)//loop through list
{
int hold = intList.get(i);//hold for comparison
if(hold <= otherH ) lower.add(hold);//if it is less than the random one, add to lower list
else higher.add(hold);//if not lower... add to higher list
}
if (k <= lower.size())//if less than or equal to
{
return qkSort(lower, k);//go through again with lower ints
}
int difference = lower.size()-higher.size();
int otherDif = intList.size()-higher.size();
if (k > difference)
{
return qkSort(higher, k-otherDif);//go through again with higher ints
}
else
return otherH;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment