Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- for(k=0;k<array.length-1;k++){
- if(array[k] > array[k+1]){
- int temp = array[k];
- array[k] = array[k+1];
- array[k+1] = temp;
- }
- }
- for(i=array.length-1;i>=0;i--){
- for(k=0;k<i;k++){
- if(array[k] > array[k+1]){
- int temp = array[k];
- array[k] = array[k+1];
- array[k+1] = temp;
- }
- }
- }
- public static void bubbleSort(int[] array){
- for (int i = 0; i < array.length - 1; i++) {
- for (int j = 0; j < array.length - i - 1; j++) {
- if(array[j] < array[j+1]){
- int tmp = array[j];
- array[j] = array[j+1];
- array[j+1] = tmp;
- }
- }
- }
- }
- procedure bubbleSort( A : list of sortable items )
- n = length(A)
- repeat
- newn = 0
- for i = 1 to n-1 inclusive do
- if A[i-1] > A[i] then
- swap(A[i-1], A[i])
- newn = i
- end if
- end for
- n = newn
- until n = 0
- end procedure
- //array of integer to be sorted
- int[] arrayToSort=new int[]{1,7,81,2,-2,9,9,6,-6};
- //repeat until we're done sorting
- while (true){
- //flag to check if we did swap number(s)
- boolean didSort=false;
- /*
- * this inner loop is being used to find numbers that need to be
- * swapped and then help in swapping them
- */
- for(int count=0;count<arrayToSort.length-1;count++){
- //check if we need to swap
- if(arrayToSort[count]>arrayToSort[count+1]){
- int temp=arrayToSort[count+1];
- arrayToSort[count+1]=arrayToSort[count];
- arrayToSort[count]=temp;
- //set our swap flag so that we will know that we did swap
- didSort=true;
- }
- }
- //check we did a swap in our last inner loop iteration if not will
- //be done sorting, then break the outer loop
- if(!didSort){
- break;
- }
- }
- //let's print the sorted array.
- for(int i=0;i<arrayToSort.length;i++){
- System.out.print(arrayToSort[i]+", ");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement