Skip to content

limcuili/JavaSorting

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 

Repository files navigation

JavaSorting

Insertion Sort

Input: a1, ... , an
Output: b1, ... , bn (the ai's in increasing order)

An iteration of Insertion Sort:
On the jth iteration, we have the sequence c1,...,cj, aj+1,...,an.
Here c1,...,cj is the numbers a1,...,aj in increasing order.

  1. Compare aj+1 with cj,cj-1,cj-2,... in this order until a place is found, ie when ci < aj+1 <= ci+1 (or aj+1 < c1).
  2. Insert aj+1 between ci and ci+1 (or at the beginning of the list).
  3. Repeat next iteration with this new c1,...,cj+1, aj+2,...,an.

Complexity: T(n) = n(n-1)/2
Worst case running time: O(n2)
Running time for ordered list: O(n)
Running time for reversed list: O(n2)
Extra memory required: O(1)

Merge Sort

Input: a1, ... , an
Output: b1, ... , bn (the ai's in increasing order)

  1. When n = 1, we are done.
  2. For n > 1, set k = floor(n/2) and recursively sort the two sequences a1,...,ak and ak+1,...,an.
  3. Merge the two sorted sequences.

Let us see how step 3 is carried out. Suppose we want to merge two sorted sequences b1,...,bk and c1,...,cl. The first element of the merged sequence is going to be min{b1,c1}. Delete this minimal element from its respective sequence and place it at the first position of the merged sequence. To find the second element of the merged sequence, compare the first elements of the two new sequences, etc. If all elements of one sequence has been deleted, then the remains of the other sequence is appended at the end of the existing merged sequence, and we are done.

Recurrence formula: T(n) = T(n-k) + n
Complexity: if using recursion tree method and assuming n = 2p, we get T(n) = 2n(log2n) = O(nlogn)
Worst case running time: O(nlogn)
Running time for ordered list: O(nlogn)
Running time for reversed list: O(nlogn)
Extra memory required: O(n)

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages