Skip to content
This repository was archived by the owner on Apr 21, 2018. It is now read-only.

Commit ba2c033

Browse files
author
YouniS Bensalah
committed
Fix bubble sort implementation.
1 parent 32c0dee commit ba2c033

1 file changed

Lines changed: 11 additions & 6 deletions

File tree

slides-10.tex

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -310,15 +310,20 @@ \subsection{Bubble Sort}
310310
\begin{exampleblock}{}
311311
\begin{lstlisting}[language=Java,basicstyle=\scriptsize]
312312
void bubbleSort(int[] list) {
313+
int n = list.length;
313314
int swap;
314-
for (int i = 1; i < list.length; i++) {
315-
for (int j = i; j > 0; j--) {
316-
if (list[j] < list[j - 1]) {
317-
swap = list[j];
318-
list[j] = list[j - 1];
319-
list[j - 1] = swap;
315+
boolean swapped = true;
316+
while (swapped) {
317+
swapped = false;
318+
for (int i = 1; i < n; i++) {
319+
if (list[i] < list[i-1]) {
320+
swap = list[i];
321+
list[i] = list[i - 1];
322+
list[i - 1] = swap;
323+
swapped = true;
320324
}
321325
}
326+
n--;
322327
}
323328
}
324329
\end{lstlisting}

0 commit comments

Comments
 (0)