Monday 20 December 2010

algorithm that implements the bubble sort method

Description:

Bubble sort is the simplest and oldest sorting technique. This method takes two elements at a time. It compare these two elements. If first elements is less than second one, they are left undistrurbed. If the first element is greater then second one then they are swapped. The procedure continues with the next two elements goes and ends when all the elements are sorted.But bubble sort is an
inefficient algorithm. The order of bubble sort algorithm is O(n2).

Algorithm:
Bubble Sort:
1. start
2. read the value of n
3. for i= 1 to n increment in steps of 1
Read the value of ith element into array
4. call function to sort (bubble_sort(a,n))
5. for i= 1 to n increment in steps of 1
print the value of ith element in the array
6. stop

BUBBLE SORT FUNCTION
1. start
2. initialise last to n
3. for i= 1 to n increment in steps of 1 begin
4. initialise x to 0
5. for i= 1 to last-1 increment in steps of 1
  begin
6.             if k[i]>k[i+1] goto step 7 otherwise goto step 5
    begin
7.                   assign k[i] to temp
8.                   assign k[i+1] to k[i]
9.                   assign temp to k[i+1]
10.                   increment x by 1
   end-if

end inner for loop
11. if ex!=0
assign last-1 to last
end for loop
          12. stop

Input/Output:

enter the range of array:3
enter elements into array:3 2 1
the sorted order is:1 2 3
enter the range of array:5
enter elements into array:56 23 34 12 8
the sorted order is: 8  12  23  34  56


More Explanation:

In a list with n elements, we need up to n-1 sort passes to order the list. With each sort pass, we increase the size of the sorted list by one (and decrease the size of the unsorted list by one).The algorithm finds the smallest value in the unsorted list and moves it to the next available position in the sorted list. Then, the barrier moves. In a bubble sort, the algorithm divides a list into two sub-lists – one sorted and one unsorted. An imaginary barrier separates the two lists.





VIVA QUESTIONS


1) Define bubble sort ?
Ans: : Bubble sort is the simplest and oldest sorting technique. This method takes two elements at a time. It compare these two elements. If first elements is less than second one, they are left undistrurbed. If the first element is greater then second one then they are swapped. The procedure continues with the next two elements goes and ends when all the elements are sorted.

2) display the efficiency of bubble sort ?
Ans : O(n2)



No comments:

Post a Comment