Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Bubble sort

807600Nov 17 2007 — edited Nov 19 2007
I wrote this code for a bubble sort:
void bubbleSort(int[] a, int first, int last) 
	{
		for (int index = first; index <= last - 1; index++)
			for (int element = first; element < last - index; element++)
			{
				if (comp(a[element], a[element + 1]) > 0)
					swap(a, element + 1, element);
			}
	}
I want to skip unnecessary passes and have the method do less work by remembering where the last swap occurred and only check up to this position on the next pass through the array. When no swaps occur during the last pass, the index of the last swap for this pass would be zero indicating that no further passes are necessary. Any ideas how to implement this?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 17 2007
Added on Nov 17 2007
7 comments
303 views