Sorting algorithms/Pancake sort: Difference between revisions
Content added Content deleted
Line 2,249: | Line 2,249: | ||
public static void main(String[] aArgs) { |
public static void main(String[] aArgs) { |
||
List<Integer> numbers = Arrays.asList( 1, 5, 4, |
List<Integer> numbers = Arrays.asList( 1, 5, 4, 2, 3, 2, 8, 6, 7 ); |
||
System.out.println("Initial list: " + numbers); |
System.out.println("Initial list: " + numbers); |
||
pancakeSort(numbers); |
pancakeSort(numbers); |
||
Line 2,256: | Line 2,256: | ||
private static void pancakeSort(List<Integer> aList) { |
private static void pancakeSort(List<Integer> aList) { |
||
for ( int i = aList.size() - 1; i >= 0; i-- ) { |
for ( int i = aList.size() - 1; i >= 0; i-- ) { |
||
int index = IntStream. |
int index = IntStream.rangeClosed(0, i).boxed().max(Comparator.comparing(aList::get)).get(); |
||
if ( index != i ) { |
if ( index != i ) { |
||
Line 2,266: | Line 2,266: | ||
private static void flip(List<Integer> aList, int aIndex) { |
private static void flip(List<Integer> aList, int aIndex) { |
||
if ( aIndex > 0 ) { |
|||
Collections.reverse(aList.subList(0, aIndex + 1)); |
|||
System.out.println("flip 0.." + aIndex + " --> " + aList); |
|||
} |
|||
} |
} |
||
Line 2,274: | Line 2,276: | ||
{{ out }} |
{{ out }} |
||
<pre> |
<pre> |
||
Initial list: [1, 5, 4, |
Initial list: [1, 5, 4, 2, 3, 2, 8, 6, 7] |
||
flip 0.. |
flip 0..6 --> [8, 2, 3, 2, 4, 5, 1, 6, 7] |
||
flip 0.. |
flip 0..8 --> [7, 6, 1, 5, 4, 2, 3, 2, 8] |
||
flip 0.. |
flip 0..7 --> [2, 3, 2, 4, 5, 1, 6, 7, 8] |
||
flip 0.. |
flip 0..4 --> [5, 4, 2, 3, 2, 1, 6, 7, 8] |
||
flip 0.. |
flip 0..5 --> [1, 2, 3, 2, 4, 5, 6, 7, 8] |
||
flip 0.. |
flip 0..2 --> [3, 2, 1, 2, 4, 5, 6, 7, 8] |
||
flip 0.. |
flip 0..3 --> [2, 1, 2, 3, 4, 5, 6, 7, 8] |
||
flip 0.. |
flip 0..2 --> [2, 1, 2, 3, 4, 5, 6, 7, 8] |
||
flip 0.. |
flip 0..1 --> [1, 2, 2, 3, 4, 5, 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> |
</pre> |
||