samedi 28 mars 2015

What's wrong with my implementation of the Dutch National flag algorithm?



Here's the original question



Give you an array which has n integers,it has both positive and negative integers.Now you need sort this array in a special way.After that,the negative integers should in the front,and the positive integers should in the back.Also the relative position should not be changed. eg. -1 1 3 -2 2 ans: -1 -2 1 3 2.



My Java code (translated from Wikipedia's pseudocode)



package ThreewayPartition;

import java.util.Arrays;

public class ThreewayPartition {
public void sort(int[] input, int mid) {
int i=0;
int j=0;
int n = input.length - 1;

while (j <= n) {
if (input[j] < mid) {
swap(input, i, j);
i++;
j++;
} else if (input[j] > mid) {
swap(input, j, n);
n--;
} else {
j++;
}
}
}

private void swap(int[] arr, int j, int k) {
int tmp = arr[j];
arr[j] = arr[k];
arr[k] = tmp;
}

public static void main(String[] args) {
int[] input = {-1, 1, 3, -2, 2};
ThreewayPartition twp = new ThreewayPartition();
twp.sort(input, 0);
System.out.println(Arrays.toString(input));
}
}


I get this output: [-1, -2, 3, 2, 1] instead of [-1, -2, 1, 3, 2]




Aucun commentaire:

Enregistrer un commentaire