2015-10-21 2 views
2

Это имеет смысл для меня с точки зрения логики, однако мои выходы являются последним числом рандомизированного числа массива снова и снова. Я подозреваю, что переменная постоянно помещается в то, что печатается. понимание был бы рад.bubble sort output error

import java.util.Arrays; 
import java.util.Scanner; 
class BubbleSort 
{ 

    public static void main(String args[]) { 
     Scanner inputScanner; 
     inputScanner = new Scanner(System.in); 
     System.out.println("please enter the size of the array"); 
     int n = Integer.parseInt (inputScanner.nextLine()); 
     //1. call upon array to fill said array with random numbers the size of n. 
     int[] filledArray = inputArray(n); 
     //2. print before sort array 
     printArray(filledArray, n); 
     //3. call the selection sort function 
     long startTime = System.currentTimeMillis(); 

     int[] theSortedArray = sortArray(filledArray, n); //calculates milliseconds 
     long endTime = System.currentTimeMillis(); 
     long timeResult = startTime - endTime; 

     //4. print sorted array 
     printSortedArray(theSortedArray, n); 

     System.out.println("ms(" + timeResult + ")"); // prints millaseconds after sorted numbers are printed out. 

    } 
    //1. fill array with random numbers 
    public static int[] inputArray(int numberOfValues){ 
     int [] arrayToFill = new int [numberOfValues];  
     for(int i = 0;i<numberOfValues;i++){ 

      double fraction = Math.random() * numberOfValues; 
      int integer = (int)fraction + 1; 
      arrayToFill[i] = integer; 

      //calculate a random number multiply by parameter(n) add one so it dosent 
      // equal 0 cast it as an integer so it Is useable then return to main. 

     } 
     return arrayToFill; 
    } 
    //2. print out presort array 
    public static void printArray(int[]preSortArray, int numberOfValues){ 
     System.out.print("The unsorted numbers are "); 
     System.out.print("["); 
     for(int i = 0;i<numberOfValues;i++){ 
      Arrays.toString(preSortArray); 
      System.out.print(preSortArray[i] + ","); 

     } 
     System.out.println("]."); 
    } 
    // sorts the array 
    public static int[] sortArray(int[] preSortArray, int numberOfValues) { 

     for(int i=0;i<numberOfValues;i++) { 
      int tempNum = i; 

      for(int j=i+1;j<numberOfValues;j++){ 
       int tempNumTwo = j; 
       int swap = 0; 

       if(preSortArray[tempNum] > preSortArray[tempNumTwo]) { 
        swap = preSortArray[tempNumTwo]; 
        preSortArray[i] = preSortArray[tempNumTwo]; 
        preSortArray[tempNum] = swap; 
       } 
      } 
     }return preSortArray; 
    } 
    //prints the sorted array 
    public static void printSortedArray(int [] sortedArray, int numberOfValues){ 
     System.out.print("The sorted set of numbers is ["); 
     for(int i = 0;i<numberOfValues;i++) { 
      Arrays.toString(sortedArray); 
      System.out.print(sortedArray[i] + ", "); 
     } 
     System.out.println("].");         
    } 
} 

ответ

0

Попробуйте

public static int[] sortArray(int[] preSortArray, int numberOfValues) { 
    int temp; 
    for(int i=0; i < numberOfValues.length-i; j++) { 

     for(int j=1; j < numberOfValues.length-i; j++){ 
     if(numberOfValues[j-1] > numberOfValues[j]); 
      swap = preSortArray[tempNumTwo]; 
      preSortArray[j-1] = numberOfValues[j]; 
      preSortArray[tempNum] = swap; 
      } 
    } 
}return preSortArray; 
}   
0

Во-первых, ваш код для свопинга не так! Вторая линия должна быть:

preSortArray[i] = preSortArray[tempNumTwo];

Во-вторых, ваша реализация пузырьковой сортировки тоже неправильно. На каждой итерации мы не сравниваем i-е число с j-м номером! Мы сравниваем два последовательных числа. Вот скорректированная версия Ваш код:

public static int[] sortArray(int[] preSortArray, int numberOfValues) { 

    for(int i=0;i<numberOfValues - 1;i++) { 
    int tempNum = i; 

    for(int j=i+1;j<numberOfValues;j++, tempNum++){ 
     int tempNumTwo = j; 
     int swap = 0; 

     if(preSortArray[tempNum] > preSortArray[tempNumTwo]) { 
     swap = preSortArray[tempNumTwo]; 
     preSortArray[tempNumTwo] = preSortArray[tempNum]; 
     preSortArray[tempNum] = swap; 

     } 

    } 

    }return preSortArray; 

}