SQL

Wednesday, 16 April 2014

Bubble sort


This Exercise has taken from Java How to Program 
The bubble sort presented in Fig. 7.10 is inefficient for large arrays. Make the following simple
modifications to improve the performance of the bubble sort:
a) After the first pass, the largest number is guaranteed to be in the highest-numbered element
of the array; after the second pass, the two highest numbers are “in place”; etc. Instead
of making nine comparisons on every pass, modify the bubble sort to make eight
comparisons on the second pass, seven on the third pass, etc


public class BubbleSort {
	public static void main (String args[]){
		
		int []array= {25,7,10,3,9,48,5,6};
		for (int j = 1; j <array.length; j ++){		
			for (int i = 0; i <array.length-j; i ++){
				int temp = array [i];
				if (array[i]> array [i+1]){
					array [i] = array [i+1];
					array [i+1]=temp;
				}
			}
		}
		for (int i = 0; i <array.length; i ++){
			System.out.printf("\t"+array[i]);
		}
	}
}

Post a Comment