Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class ShakerSort {
- private static void printNumbers(int[] input) {
- for (int i = 0; i < input.length; i++) {
- System.out.print(input[i] + " ");
- }
- System.out.print(System.lineSeparator());
- }
- static void swap(int array[], int i, int j) {
- int temp = array[i];
- array[i] = array[j];
- array[j] = temp;
- }
- static void MybubbleSort(int array[]) {
- printNumbers(array);
- /*
- System.out.print("Here "+array.length+System.lineSeparator());
- */
- for (int i = 0; i < array.length; i++) {
- /*
- System.out.print(i+" "+System.lineSeparator());
- */
- for (int j = 1; j < array.length - i; j++) {
- /*
- System.out.print(i + " " + j + System.lineSeparator());
- */
- /* Swap Elements */
- if (array[j - 1] > array[j]) {
- swap(array, j - 1, j);
- }
- }
- printNumbers(array);
- }
- }
- static void bubbleSort(int array[]) {
- for (int i = array.length - 1; i >= 0; i--) {
- boolean flipped = false;
- for (int j = 1; j <= i; j++) {
- if (array[j - 1] > array[j]) {
- swap(array, j - 1, j);
- flipped = true;
- }
- }
- if (!flipped) break;
- printNumbers(array);
- }
- }
- /* A variation of bubblesort */
- static void shakerSort(int array[], int n) {
- int countMin = 0;
- int countMax = 0;
- boolean done = false;
- for (int k = 0; k < (array.length + 1) / 2; ++k) {
- done = true;
- /* Smallest in front */
- for (int j = array.length - 1; j > countMin; j--) {
- if (array[j - 1] > array[j]) {
- swap(array, j - 1, j);
- done = false;
- }
- }
- countMin++;
- printNumbers(array);
- /* Biggest in rear */
- for (int j = countMax; j < array.length - 1; j++) {
- if (array[j] > array[j + 1]) {
- swap(array, j, j + 1);
- done = false;
- }
- }
- countMax++;
- printNumbers(array);
- if (done) break;
- }
- }
- public static void main(String[] args) throws IOException {
- int i;
- BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
- String s = stdin.readLine();
- int n = Integer.parseInt(s);
- s = stdin.readLine();
- String[] pom = s.split(" ");
- int[] a = new int[n];
- for (i = 0; i < n; i++)
- a[i] = Integer.parseInt(pom[i]);
- shakerSort(a, n);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment