|
| 1 | +package me.ramswaroop.arrays.sorting; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by IntelliJ IDEA. |
| 7 | + * |
| 8 | + * @author: ramswaroop |
| 9 | + * @date: 10/26/15 |
| 10 | + * @time: 9:20 PM |
| 11 | + */ |
| 12 | +public class PancakeSort { |
| 13 | + |
| 14 | + /** |
| 15 | + * Sorts the array {@param a} in-place in O(n^2) time complexity. |
| 16 | + * <p/> |
| 17 | + * This can also be seen as: Sort the array {@param a} using a method |
| 18 | + * {@code reverse(int[] a, int end)} which reverses array {@code int[] a} |
| 19 | + * from {@code 0} index till {@code end} index (both inclusive). |
| 20 | + * |
| 21 | + * @param a |
| 22 | + */ |
| 23 | + public static void sort(int[] a) { |
| 24 | + |
| 25 | + int maxIndex; // max element's index |
| 26 | + int unsortedIndex = a.length - 1; // index till which elements are unsorted |
| 27 | + |
| 28 | + while (unsortedIndex > 0) { |
| 29 | + maxIndex = 0; |
| 30 | + // find max element's index |
| 31 | + for (int j = 1; j <= unsortedIndex; j++) { |
| 32 | + if (a[j] > a[maxIndex]) { |
| 33 | + maxIndex = j; |
| 34 | + } |
| 35 | + } |
| 36 | + reverse(a, maxIndex); // bring the max element to the front |
| 37 | + reverse(a, unsortedIndex); // move the max element to its appropriate index |
| 38 | + unsortedIndex--; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Reverses array {@param a} from {@code 0} index |
| 44 | + * till {@code end} index. |
| 45 | + * |
| 46 | + * @param a |
| 47 | + * @param end |
| 48 | + */ |
| 49 | + public static void reverse(int[] a, int end) { |
| 50 | + int temp; |
| 51 | + for (int i = 0; i <= end / 2; i++) { |
| 52 | + temp = a[i]; |
| 53 | + a[i] = a[end - i]; |
| 54 | + a[end - i] = temp; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String a[]) { |
| 59 | + int[] ar = {1, 2, 3, 4, 5, 6}; |
| 60 | + System.out.println(Arrays.toString(ar)); |
| 61 | + sort(ar); |
| 62 | + System.out.println(Arrays.toString(ar)); |
| 63 | + ar = new int[]{3, 4, 7, 1, 9, 0}; |
| 64 | + System.out.println(Arrays.toString(ar)); |
| 65 | + sort(ar); |
| 66 | + System.out.println(Arrays.toString(ar)); |
| 67 | + ar = new int[]{6, 5, 4, 3, 2, 1}; |
| 68 | + System.out.println(Arrays.toString(ar)); |
| 69 | + sort(ar); |
| 70 | + System.out.println(Arrays.toString(ar)); |
| 71 | + ar = new int[]{}; |
| 72 | + System.out.println(Arrays.toString(ar)); |
| 73 | + sort(ar); |
| 74 | + System.out.println(Arrays.toString(ar)); |
| 75 | + ar = new int[]{1}; |
| 76 | + System.out.println(Arrays.toString(ar)); |
| 77 | + sort(ar); |
| 78 | + System.out.println(Arrays.toString(ar)); |
| 79 | + } |
| 80 | +} |
0 commit comments