Skip to content

Instantly share code, notes, and snippets.

@greenlaw110
Last active August 29, 2015 14:04
Show Gist options
  • Save greenlaw110/6af018210da697578688 to your computer and use it in GitHub Desktop.
Save greenlaw110/6af018210da697578688 to your computer and use it in GitHub Desktop.
Sort array by number symbol, negative should all go left and positive should all go right
import java.util.Arrays;
/**
* Created by luog on 22/07/2014.
*/
public class SortIntArray {
private static int[] ia;
private static void initArray(String[] args) {
if (args.length > 0) {
ia = new int[args.length];
for (int i = 0; i < args.length; ++i) {
ia[i] = Integer.parseInt(args[i]);
}
} else {
ia = new int[]{2, -2, 3, 1, -4, -5};
// int len = 23;
// ia = new int[len];
// for (int i = 0; i < len; ++i) {
// ia[i] = _.random(C.range(-20, 20));
// }
}
}
private static void sortArray() {
int l = ia.length;
int pLastNegative = -1;
for (int j = l - 1; j >= 0; --j) {
if (ia[j] < 0) {
pLastNegative = j;
break;
}
}
if (pLastNegative == -1) return;
int pNonNegative = -1;
long temp = Long.MAX_VALUE;
for (int i = 0; i < pLastNegative + 1; ++i) {
if (ia[i] < 0) {
if (pNonNegative > -1) {
if (temp == Long.MAX_VALUE) {
int t = ia[i];
ia[i] = ia[pNonNegative];
ia[pNonNegative] = t;
} else {
ia[pNonNegative] = ia[i];
ia[i] = (int)temp;
temp = Long.MAX_VALUE;
}
pNonNegative = pNonNegative + 1;
}
} else {
if (pNonNegative == -1) {
pNonNegative = i;
} else {
if (temp == Long.MAX_VALUE) {
temp = ia[i];
ia[i] = ia[i - 1];
} else {
int t = (int)temp;
temp = ia[i];
ia[i] = t;
}
}
}
System.out.println("i: " + i + "\tp: " + pNonNegative + "\tt:" + temp);
printArray();
}
}
private static void printArray() {
System.out.println(Arrays.toString(ia));
}
public static void main(String[] args) {
initArray(args);
printArray();
sortArray();
printArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment