1

Say I have an array as such:

[9, 7, 13, 24, 2, 16, 3, 10]

And I wanted to sort the array based off of the int 9, where all values less than 9 are to its left, and all values greater are to its right, could a version of selection sort be used?

A little stumped here

5
  • 5
    Confused - you want all the ints lower than 9 to its left, values higher than 9 to its right? Isn't that just a regular sort? Commented Sep 8, 2015 at 1:55
  • 1
    I think the question is to have to all elements less than 9 on the left and more than 9 on the right. There is no question of sorting amongst the elements on the left/right. Potentially, this is a one-step [en.wikipedia.org/wiki/Quicksort Quicksort] problem. Commented Sep 8, 2015 at 1:59
  • Yea I was thinking more quicksort myself, where the int 9 is the pivot, and all values are sorted around the pivot Commented Sep 8, 2015 at 2:02
  • @Sean Are you still looking for a solution for this problem? I have a clean and extremely short solution to this problem. Commented Sep 13, 2015 at 21:48
  • @Sean , please check if my answer is what you need Commented Sep 16, 2015 at 11:21

1 Answer 1

1

What you want should be something like one step of quick sort.

I modify a little so that you can pass an pivot needed as a parameter :

public static void main(String[] args) {
    int[] a = new int[]{9,7,13,24,2,16,3,10};
    System.out.println(partition(a,9));//use value 9 as pivot 
    System.out.println(Arrays.toString(a));

}

private static int  partition(int[] a, int pivot){
    int pivotIndex = 0;

    for(int i=0;i<a.length;i++){//find initial pivot Index
        if(a[i]==pivot) {
            pivotIndex = i;
            break;
        }
    }


    int low = 0;
    int high = a.length-1;

    while(low<high){
        while(low<high&&a[high]>=pivot) high--;
        a[pivotIndex] = a[high];
        pivotIndex = high;

        while(low<high&&a[low]<=pivot) low++;
        a[pivotIndex] = a[low];
        pivotIndex= low;
    }

    //Actual pivotIndex finded
    a[pivotIndex] = pivot;

    return pivotIndex;
}

output:

3
[3, 7, 2, 9, 24, 16, 13, 10]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.