In java:
import java.util.Arrays; /** * Does a bubble sort without allocating extra memory * */ public class Sort { // Implements bubble sort very inefficiently for CPU but with minimal variable declarations public static void sort(int[] array) { int index=0; while(true) { next: { // Scan for correct sorting. Wasteful, but avoids using a boolean parameter for (index=0;index<array.length-1;index++) { if (array[index]>array[index+1]) break next; } // Array is now correctly sorted return; } // Now swap. We don't need to rescan from the start for (;index<array.length-1;index++) { if (array[index]>array[index+1]) { // use xor trick to avoid using an extra integer array[index]^=array[index+1]; array[index+1]^=array[index]; array[index]^=array[index+1]; } } } } public static void main(final String argv[]) { int[] array=new int[] {4,7,2,4,1,10,3}; sort(array); System.out.println(Arrays.toString(array)); } }
Actually, using the trick suggested by Nils , you can eliminate even one remaining int allocation - although, of course, this will add to the stack instead ...
Bill Michell Sep 25 '08 at 13:35 2008-09-25 13:35
source share