java - Sorting an Array of int using BubbleSort -


why printed out array not sorted in below code?

public class bubblesort {     public void sortarray(int[] x) {//go through array , sort smallest highest       for(int i=1; i<x.length; i++) {          int temp=0;          if(x[i-1] > x[i]) {             temp = x[i-1];             x[i-1] = x[i];             x[i] = temp;          }       }    }     public void printarray(int[] x) {       for(int i=0; i<x.length; i++)         system.out.print(x[i] + " ");    }     public static void main(string[] args) {       // testbubblesort       bubblesort b = new bubblesort();       int[] num = {5,4,3,2,1};       b.sortarray(num);       b.printarray(num);       } } 

you need 2 loops implement bubble sort .

sample code :

public static void bubblesort(int[] numarray) {      int n = numarray.length;     int temp = 0;      (int = 0; < n; i++) {         (int j = 1; j < (n - i); j++) {              if (numarray[j - 1] > numarray[j]) {                 temp = numarray[j - 1];                 numarray[j - 1] = numarray[j];                 numarray[j] = temp;             }          }     } } 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -