Bubble Sort Optimized

I'd like to optimize the bubble sort algorithm. For some reason my algorithm below has worst performance than the original bubble sort. Any ideas what I did wrong? Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void bubbleSortOptimized(int myArray[], int iLength) 
 {
	 
	
		for(int i=0; i<iLength; i++)
		{ 
			bool swapped = false;
		
			for(int j=0; j<iLength-i-1; j++)
			{
			if(myArray[j]>myArray[j+1])
				{
				swapped = true;
				int temp = myArray[j+1];
				myArray[j+1] = myArray[j];
				myArray[j] = temp;
				}
			}
		// No Swapping, array is sorted
		if(!swapped){ 
		return; 
		} 
		}
}
After each inner loop remember 'j' of your last swapped element and use it as your new termination condition of your outer loop.
Topic archived. No new replies allowed.