Professional Documents
Culture Documents
Simplesorts1 PDF
Simplesorts1 PDF
Bubble sort
complexity
Bubble sort void bubbleSort(int arr[]){
int i;
Selection sort int j;
Insertion sort int temp;
for(i = arr.length-1; i > 0; i--){
for(j = 0; j < i; j++){
if(arr[j] > arr[j+1]){
temp = arr[j]; swap adjacent
arr[j] = arr[j+1]; elements, if in
arr[j+1] = temp; the wrong
}// order
}// end inner loop
}//end outer loop}// end bubble sort
1
Bubble sort of a linked list Complexity of bubble sort on lists
Node border = null; // first node in the sorted part Same complexity as for arrays O(n2):
while (border != head) { First time we iterate until we see a null (swapping
Node current = head; // start from the first node elements)
while (current.next != border) { Second time we iterate until we see the last node;
if (current.element > current.next.element) { each time the border is one link closer to the head
E element v = current.element; swap with the of the list
current.element = current.next.element;next node if until border == head.
current.next.element = v; elements out
} of order
current = current.next; head null
} head null
border
border = current; // the sorted part increases by one head null
} head null
2
Complexity of insertion sort Insertion sort on linked lists
In the worst case, has to make n(n-1)/2 This is a suitable sorting method for doubly linked
comparisons and shifts to the right lists
also O(n2) worst case complexity We can just insert a node in a sorted portion of
best case: array already sorted, no shifts. linked list in constant time, dont need to shift
other nodes to make space for it (but need to find
the place):
10 12 23 5 14
10 12 23 14 10 12 23 14
5 5
10 12 23 14 10 12 23 14
5 5
3
Implementation of insertion sort on
Insertion sort on linked lists
linked lists
This is a suitable sorting method for doubly linked So this time assume we have a doubly-linked list
lists We will move nodes rather than swapping
We can just insert a node in a sorted portion of elements
linked list in constant time, dont need to shift Assume we have DNode class which has fields
other nodes to make space for it (but need to find element, next and prev
the place):
DList class has head field
10 12 23 14
4
Implementation of insertion sort on
linked lists
This is O(n2): in each iteration through the outer loop,
we move border one step to the right
In the inner loop, we iterate through the sorted portion,
looking for a place to insert
In the worst case (list sorted in reverse order) will have to
do 1+2++n-1 comparisons in the sorted part.
It would have been better (if we planned to use insertion
sort for sorting almost sorted lists) to search for the
insertion point not from the head of the list going towards
the border, but from the border going towards the head; if
the list is almost sorted, this would result in a shorter
iteration.