티스토리 뷰

data structure

Sort

summercat 2022. 1. 19. 18:06

sort: to arrange something in an order
to use fast algorithms ex. binary search, array should be sorted

1. bubble sort
- not used very much (there are a lot of better algorithms)
- select first 2 items of an array and compare them
> if left is bigger than the right, swap them
> do the same with index 1, 2
> repeat ….
> when it reaches the end of an array, the first cycle of bubble sort ends
> do it all over again from the first item
- time complexity = O(N^2)

2. selection sort
- keep track of the location of the lowest item from the first item in a variable
> swap the lowest item with the first item
> next cycle starts from the second item
- time complexity = O(N^2)
- faster than bubble sort (less swaps occur)

ex. [5, 2, 6, 3, 1, 4]
int a = lowest item
a = 5 > a = 2 > a = 2 > a = 2 > a= 1 > a = 4
swap a with 5
start from second item (2)

3. insertion sort
- faster than selection sort (selection sort scans all the elements, insertion sort scans items that are needed)
- time complexity = O(N^2)


three sort algorithms are expressed the same in the Big O notation, but their speed may differ.

'data structure' 카테고리의 다른 글

Type of Time Complexity (Big O notation)  (0) 2022.01.19
Search Algorithms (Binary Search/ Linear Search)  (0) 2022.01.19
Array  (0) 2022.01.19
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함