by: Luisito G. TrinidadMSIT
Bubble Sort
• Sorting takes an unordered collection and makes it an ordered one.
• Bubble sort algorithm*:• Compare adjacent elements. If the first is greater than the
second, swap them. • Do this for each pair of adjacent elements, starting with the
first two and ending with the last two. At this point the last element should be the greatest.
• Repeat the steps for all elements except the last one. • Keep repeating for one fewer element each time, until you
have no more pairs to compare • Time complexity: O(n2)
NOTE: As always, it's better if you don't write your own sorts. Java has better sort methods in java.util.Arrays.sort(...) and java.util.Collections.sort(...). But sorts are excellent practice, and are a technique that all students are expected to understand to some extent.
Working of bubble sort algorithm???
Sample value
12,9,4,99,120,1,3,10
SAMPLE CODE
public class bubbleSort{public static void main(String a[]){int i;int array[] = {12,9,4,99,120,1,3,10,23};
System.out.println("Values Before the sort:\n");for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");System.out.println();
bubble_srt(array, array.length);System.out.print("Values after the sort:\n");
for(i = 0; i <array.length; i++)System.out.print(array[i]+" ");System.out.println();System.out.println("PAUSE");
}public static void bubble_srt( int a[], int n ){int i, j,t=0;
for(i = 0; i < n; i++){for(j = 1; j < (n-i); j++){if(a[j-1] > a[j]){
t = a[j-1];a[j-1]=a[j];a[j]=t;}
}}}
}
Bin Sort
Bucket sort, or bin sort, is a sorting algorithm that works by partitioning an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a cousin of radix sort in the most to least significant digit flavour. Bucket sort is a generalization of pigeonhole sort. Since bucket sort is not a comparison sort, the Ω(n log n) lower bound is inapplicable. The computational complexity estimates involve the number of buckets.
Elements are distributed among bins
End.
www.bantayog.net63.net
Top Related