|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Can someone please help me out!!
Can someone explain this sort algorithm to me and how i can make a more efficient version, justifying the changes.
for (int p = 0; p<n-1; p++) for (int counter = 0;counter < n-1; counter++) if (a[counter]> a[counter+1]) swap(a, counter, counter+1); Apreciate all help. |
|
#2
|
||||
|
||||
|
What happens if you set counter to equal p instead of zero?
|
|
#3
|
|||
|
|||
|
This code implements the bubble sort algorithm.
Code:
//do n-1 passes
for (int p = 0; p<n-1; p++)
{
//each pass consists of going left to right in the array and swapping
//adjacent items that are out of order
for (int counter = 0;counter < n-1; counter++)
{
//if out of order swap
if (a[counter]> a[counter+1])
swap(a, counter, counter+1);
}
}
Suppose we have the following list: 1, 5, 2, 0. Bubble sort does the following: Pass 1: 1, 5, 2, 0 - compare the 1 & 5. Out of order? No. 1, 5, 2, 0 - compare the 5 & 2. Out of order? Yes. Swap! 1, 2, 5, 0 - compare the 5 & 0. Out of order? Yes. Swap! 1, 2, 0, 5 Pass 2: 1, 2, 0, 5 - compare the 1 & 2. Out of order? No. 1, 2, 0, 5 - compare the 2 & 0. Out of order? Yes. Swap! 1, 0, 2, 5 - compare the 2 & 5. Out of order? No. Pass 3: 1, 0, 2, 5 - compare the 1 & 0. Out of order? Yes. Swap! 0, 1, 2, 5 - compare the 1 & 2. Out of order? No. 0, 1, 2, 5 - compare the 2 & 5. Out of order? No. Bubble sort does one more unnecessary pass and then stops. For more help, www.NeedProgrammingHelp.com |
![]() |
| Viewing: Dev Articles Community Forums > Programming > Java Development > Can someone please help me out!! |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|