Beruflich Dokumente
Kultur Dokumente
5 3
Bubble Sort Algorithm in Java
void bubbleSort(int List[])
{ int temp;
int size = List.length;
for (i = 0; i < size - 1; i++)
{
for (j = 0; j < size – (i + 1); j++)
{
if (List[j] > List[j+1])
{ //swap
temp = List[j];
List[j] = List[j+1];
List[j+1] = temp;
}
} Time complexity of the Bubble Sort
} algorithm is O(n2). Think why?
}
Selection Sort: Informal
Suppose we want to sort an array in ascending
order:
Locate the smallest element in the array; swap it
with element at index 0
Then, locate the next smallest element in the array;
swap it with element at index 1.
Continue until all elements are arranged in order
Selection Sort in Action
3 14 14 14
15 15 15 15
45 45 45 45
40 40 40 40
8 8 8 22
12 12 12 12
5 5 22 8
22 22 5 5
14 3 3 3
Selection Sort in Action
14 14 22 22
15 15 15 40
45 45 45 45
40 40 40 15
22 22 14 14
12 12 12 12
8 8 8 8
5 5 5 5
3 3 3 3
Selection Sort in Action
22 45 45 45
40 40 40 40
45 22 22 22
15 15 15 15
14 14 14 14
12 12 12 12
8 8 8 8
5 5 5 5
3 3 3 3
Selection Sort Algorithm in Java
void selectionSort(int List[])
{
int temp, min;
int size = List.length;
for (i = 0; i < size; i++){
min = i;
for (j = i + 1; j < size; j++)
{
if (List[j] < List[min])
{min = j;}
}
temp = List[min];
List[min] = List[i]; //swap
List[i] = temp;
} Time complexity of the Selection
} Sort algorithm is O(n2). Think why?
Bubble Sort vs. Selection Sort
Insertion Sort
Insertion Sort
… by shifting first 36
towards right…
22
Insertion Sort
Insertion Sort