Problem 27 Java How to count passes and swaps?

Back to General discussions forum

V_Mischenko     2017-01-22 03:40:21

This is my code. I've trayed different releases of bubble sort. All of these works correct. But, how can i count passes and swaps?

import java.util.Scanner;
public class BubbleSort {
public static int nPasses=0;
public static int nSwaps=0;
public static void main(String[] args) {

     Scanner in = new Scanner(System.in);
    int numTr = in.nextInt();
    int[] tosortAr;
    tosortAr = new int[numTr];
    for(int i = 0; i<numTr; i++) 
            {
              tosortAr[i] = in.nextInt();
            }
    in.close();

    bubbleSort(tosortAr);

    /* 
    ucomment to see sorted array
    for(int i=0;i<tosortAr.length;i++)
            System.out.print("tosortAr = "+tosortAr[i]+" ");
    */
    System.out.println();
    System.out.println(nPasses+" "+nSwaps);
}
// сортировка пузырьком
public static void bubbleSort(int[] arr) {
  boolean swapped = true;
  int j = 0;
  int tmp;
  int len = arr.length;
  while (swapped) {
        swapped = false;
        j++;
        for (int i = 0; i < len - j; i++) {  

              if (arr[i] >= arr[i + 1]) {                          
                    tmp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = tmp;
                    swapped = true;
                    BubbleSort.nSwaps++;
              }
        }  
        BubbleSort.nPasses++;
  }
}

}

An other:

public static void buble_sort(int[] arr) {
    int i=arr.length;

    while(--i>=0)
    {
        for(int j=0; j<i; j++)
        {
            if (arr[j]>arr[j+1])

            {

                 int tmp = arr[j] ;

                    arr[j] = arr[j+1];

                    arr[j+1]= tmp;

            }
        }
    }
}

But, where cout passes and swaps? What is wrong?

other code:

public static void bubbleSort2(int[] arr){
     //int tmp = 0;
     int len =arr.length;
    for (int i = 0; i < (len - 1); i++) {

        for (int j = 1; j < (len - i); j++) {
            if (arr[j - 1] < arr[j]) {
                int tmp = arr[j - 1];
                arr[j - 1] = arr[j];
                arr[j] = tmp;
                                    BubbleSort.nSwaps++;
            }
        }

             BubbleSort.nPasses++;
            }                

}

/*
run:
8
3 1 4 1 5 9 2 6

7 19
*/
Quandray     2017-01-22 07:34:30
User avatar

It looks like you've now solved it.

Please login and solve 5 problems to be able to post at forum