|
| 1 | +/** |
| 2 | + * Pancake Sort |
| 3 | + * -------------------------- |
| 4 | + * It is a sorting algorithm of O(n^2) algorithm which sorts like selection sort |
| 5 | + * by moving the minimum to the front by reversing the array till its index. |
| 6 | + */ |
| 7 | + |
| 8 | +// Importing required libraries |
| 9 | +import 'dart:io'; |
| 10 | + |
| 11 | +// Utility function to find maximum of the array |
| 12 | +int findMax(List array, int n){ |
| 13 | + int max_value = array[0]; |
| 14 | + int max_index = 0; |
| 15 | + for (int i = 0; i < n; i ++){ |
| 16 | + if (max_value < array[i]){ |
| 17 | + max_value = array[i]; |
| 18 | + max_index = i; |
| 19 | + } |
| 20 | + } |
| 21 | + return max_index; |
| 22 | +} |
| 23 | + |
| 24 | +// Utility function to flip an array from an index |
| 25 | +void flip(List array, int i){ |
| 26 | + int start = 0, temp; |
| 27 | + while (start < i){ |
| 28 | + temp = array[start]; |
| 29 | + array[start] = array[i]; |
| 30 | + array[i] = temp; |
| 31 | + start ++; |
| 32 | + i --; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +// Function to sort a list using pancake sort |
| 37 | +void pancakeSort(List array, int n){ |
| 38 | + for (int i = n; i > 1; i --){ |
| 39 | + int max_index = findMax(array, i); |
| 40 | + if (max_index != i - 1){ |
| 41 | + flip(array, max_index); |
| 42 | + flip(array, i - 1); |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | +// Driver method of the program |
| 47 | +void main(){ |
| 48 | + print("Enter number of elements of the array:"); |
| 49 | + var input = stdin.readLineSync(); |
| 50 | + int n = int.parse(input); |
| 51 | + |
| 52 | + print("Enter array elements:"); |
| 53 | + input = stdin.readLineSync(); |
| 54 | + var lis = input.split(" "); |
| 55 | + List array = lis.map(int.parse).toList(); |
| 56 | + |
| 57 | + pancakeSort(array, n); |
| 58 | + |
| 59 | + print(array.join(" ")); |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Sample Input and Output |
| 64 | + * ------------------------------------ |
| 65 | + * Enter number of elements of the array: |
| 66 | + * 10 |
| 67 | + * Enter array elements: |
| 68 | + * 10 9 8 7 6 5 4 3 2 1 |
| 69 | + * 1 2 3 4 5 6 7 8 9 10 |
| 70 | + */ |
0 commit comments