Jump to content

Sorting algorithms/Pancake sort: Difference between revisions

Line 2,242:
<syntaxhighlight>
 
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
 
public final class PancakeSort {
 
public static void main(String[] aArgs) {
List<Integer> numbers = Arrays.asList( 1, 5, 4, 6, 3, 2, 8, 6, 7 );
System.out.println("Initial list: " + numbers);
pancakeSort(numbers);
}
private static void pancakeSort(List<Integer> aList) {
for ( int i = aList.size() - 1; i >= 0; i-- ) {
int index = IntStream.range(0, i + 1).boxed().max(Comparator.comparing(aList::get)).get();
if ( index != i ) {
flip(aList, index);
flip(aList, i);
}
}
}
private static void flip(List<Integer> aList, int aIndex) {
Collections.reverse(aList.subList(0, aIndex + 1));
System.out.println("flip 0.." + ( aIndex + 1 ) + " --> " + aList);
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
Initial list: [1, 5, 4, 6, 3, 2, 8, 6, 7]
flip 0..7 --> [8, 2, 3, 6, 4, 5, 1, 6, 7]
flip 0..9 --> [7, 6, 1, 5, 4, 6, 3, 2, 8]
flip 0..1 --> [7, 6, 1, 5, 4, 6, 3, 2, 8]
flip 0..8 --> [2, 3, 6, 4, 5, 1, 6, 7, 8]
flip 0..3 --> [6, 3, 2, 4, 5, 1, 6, 7, 8]
flip 0..7 --> [6, 1, 5, 4, 2, 3, 6, 7, 8]
flip 0..1 --> [6, 1, 5, 4, 2, 3, 6, 7, 8]
flip 0..6 --> [3, 2, 4, 5, 1, 6, 6, 7, 8]
flip 0..4 --> [5, 4, 2, 3, 1, 6, 6, 7, 8]
flip 0..5 --> [1, 3, 2, 4, 5, 6, 6, 7, 8]
flip 0..2 --> [3, 1, 2, 4, 5, 6, 6, 7, 8]
flip 0..3 --> [2, 1, 3, 4, 5, 6, 6, 7, 8]
flip 0..1 --> [2, 1, 3, 4, 5, 6, 6, 7, 8]
flip 0..2 --> [1, 2, 3, 4, 5, 6, 6, 7, 8]
</pre>
 
=={{header|JavaScript}}==
908

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.