Difference between revisions of "Interview Preparation Bubble Sort"
From Embedded Systems Learning Academy
Proj user18 (talk | contribs) (Created page with "I think this ia a simplest sorting algorithm for implementation. Algorithm for placing an array of elements n in an ascending order is listed below, a. Begin from the first...") |
Proj user18 (talk | contribs) |
||
(5 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
− | I think this | + | I think this is simplest sorting algorithm among all other sorting algorithms. |
Algorithm for placing an array of elements n in an ascending order is listed below, | Algorithm for placing an array of elements n in an ascending order is listed below, | ||
+ | |||
a. Begin from the first element and start comparing two elements. | a. Begin from the first element and start comparing two elements. | ||
+ | |||
b. If the element at smaller index is greater swap the element. | b. If the element at smaller index is greater swap the element. | ||
− | c. Increment the index by one and repeat step | + | |
+ | c. Increment the index by one and repeat step 'b' for n-1 iteration. | ||
+ | |||
d. Repeat step b and C for n-1 times. | d. Repeat step b and C for n-1 times. | ||
− | Similar algorithm | + | |
+ | '''Code Snippet''' | ||
+ | <pre> | ||
+ | for(l = 0 ; l < Elecount ; l++) | ||
+ | { | ||
+ | for(j = 0; j < Elecount-l-1; j++) | ||
+ | { | ||
+ | if(array[j] > array[j+1]) | ||
+ | { | ||
+ | temp = array[j]; | ||
+ | array[j] = array[j+1]; | ||
+ | array[j+1] = temp; | ||
+ | } | ||
+ | } | ||
+ | }</pre> | ||
+ | |||
+ | Similar to above algorithm, Algorithm for placing an array of 'n' elements in descending order can be formulated with minute changes. | ||
For an array with n number of elements. Worst case complexity = О(n^2) and average complexity = О(n^2). | For an array with n number of elements. Worst case complexity = О(n^2) and average complexity = О(n^2). |
Latest revision as of 13:11, 25 November 2016
I think this is simplest sorting algorithm among all other sorting algorithms. Algorithm for placing an array of elements n in an ascending order is listed below,
a. Begin from the first element and start comparing two elements.
b. If the element at smaller index is greater swap the element.
c. Increment the index by one and repeat step 'b' for n-1 iteration.
d. Repeat step b and C for n-1 times.
Code Snippet
for(l = 0 ; l < Elecount ; l++) { for(j = 0; j < Elecount-l-1; j++) { if(array[j] > array[j+1]) { temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } }
Similar to above algorithm, Algorithm for placing an array of 'n' elements in descending order can be formulated with minute changes.
For an array with n number of elements. Worst case complexity = О(n^2) and average complexity = О(n^2).