├── Data Structure └── disjoint_set.py ├── Geometry └── number_of_intersection_points_of_two_lines_in_1_dimension.py ├── Graph ├── dijkstra_shortest_path.py ├── minimum_spanning_tree.py └── topology_sort.py ├── Miscellaneous ├── fenwick_tree.py ├── number_of_intervals_whose_sum_is_M.py ├── prefix_sum.py └── rotate_a_matrix_by_90_degree.py ├── Number Theory ├── find_all_divisors_of_a_number.py ├── gcd.py ├── is_prime_number.py ├── lcm.py └── prime_factorization.py ├── README.md ├── Searching ├── binary_search.py ├── count_the_number_of_frequencies_in_a_sorted_array.py ├── dfs_and_bfs_example_1.py ├── find_the_number_of_connected_components.py └── python_binary_search_library.py └── Sorting ├── counting_sort.py ├── insertion_sort.py ├── python_sort_library.py ├── quick_sort.py └── selection_sort.py /Data Structure/disjoint_set.py: -------------------------------------------------------------------------------- 1 | # Find the root node of x recursively. 2 | def find_parent(parent, x): 3 | if parent[x] != x: 4 | parent[x] = find_parent(parent, parent[x]) 5 | return parent[x] 6 | 7 | # Union the two sets. 8 | def union_parent(parent, a, b): 9 | a = find_parent(parent, a) 10 | b = find_parent(parent, b) 11 | if a < b: 12 | parent[b] = a 13 | else: 14 | parent[a] = b 15 | 16 | v, e = map(int, input().split()) 17 | parent = [0] * (v + 1) 18 | for i in range(1, v + 1): 19 | parent[i] = i 20 | 21 | # Process union operations. 22 | for i in range(e): 23 | a, b = map(int, input().split()) 24 | union_parent(parent, a, b) 25 | 26 | print('Root nodes for all nodes: ', end='') 27 | for i in range(1, v + 1): 28 | print(find_parent(parent, i), end=' ') 29 | 30 | print() 31 | 32 | print('Parent Table: ', end='') 33 | for i in range(1, v + 1): 34 | print(parent[i], end=' ') 35 | 36 | ''' 37 | [Input Example 1] 38 | 6 4 39 | 1 4 40 | 2 3 41 | 2 4 42 | 5 6 43 | [Output Example 1] 44 | Root nodes for all nodes: 1 1 1 1 5 5 45 | Parent Table: 1 1 1 1 5 5 46 | ''' 47 | -------------------------------------------------------------------------------- /Geometry/number_of_intersection_points_of_two_lines_in_1_dimension.py: -------------------------------------------------------------------------------- 1 | ''' Number of intersection points of two lines in 1 dimension ''' 2 | def num_of_intersect_two_lines(line_1, line_2): 3 | return max(min(line_1[1], line_2[1]) - max(line_1[0], line_2[0]) + 1, 0) 4 | 5 | # Case 1 6 | line_1 = [3, 7] 7 | line_2 = [6, 9] 8 | 9 | print(num_of_intersect_two_lines(line_1, line_2)) 10 | 11 | # Case 2 12 | line_1 = [3, 5] 13 | line_2 = [7, 9] 14 | 15 | print(num_of_intersect_two_lines(line_1, line_2)) 16 | -------------------------------------------------------------------------------- /Graph/dijkstra_shortest_path.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | import sys 3 | input = sys.stdin.readline 4 | INF = int(1e9) 5 | 6 | ''' Dijkstra Shortest Path ''' 7 | def dijkstra(start): 8 | # Set the start node. 9 | q = [(0, start)] 10 | distance[start] = 0 11 | while q: # Until the queue is empty. 12 | # Pop the node who has the shortest path. 13 | dist, now = heapq.heappop(q) 14 | # If the node is already processed, pass. 15 | if distance[now] < dist: 16 | continue 17 | # Check the adjacent nodes of the current node. 18 | for i in graph[now]: 19 | cost = dist + i[1] 20 | # If the distance is shorter when going through the current node to the adjacent node. 21 | if cost < distance[i[0]]: 22 | distance[i[0]] = cost 23 | heapq.heappush(q, (cost, i[0])) 24 | 25 | n, m = map(int, input().split()) 26 | start = int(input()) 27 | graph = [[] for i in range(n + 1)] 28 | distance = [INF] * (n + 1) 29 | 30 | for _ in range(m): 31 | a, b, c = map(int, input().split()) 32 | graph[a].append((b, c)) 33 | 34 | # Run the Dijkstra algorithm. 35 | dijkstra(start) 36 | 37 | # Print all the shortest paths to all nodes. 38 | for i in range(1, n + 1): 39 | if distance[i] == INF: 40 | print("INFINITY") 41 | else: 42 | print(distance[i]) 43 | 44 | ''' 45 | [Input Example 1] 46 | 5 6 47 | 1 48 | 5 1 1 49 | 1 2 2 50 | 1 3 3 51 | 2 3 4 52 | 2 4 5 53 | 3 4 6 54 | [Output Example 1] 55 | 0 56 | 2 57 | 3 58 | 7 59 | INFINITY 60 | ''' 61 | -------------------------------------------------------------------------------- /Graph/minimum_spanning_tree.py: -------------------------------------------------------------------------------- 1 | # Find the root node of x recursively. 2 | def find_parent(parent, x): 3 | if parent[x] != x: 4 | parent[x] = find_parent(parent, parent[x]) 5 | return parent[x] 6 | 7 | # Union the two sets. 8 | def union_parent(parent, a, b): 9 | a = find_parent(parent, a) 10 | b = find_parent(parent, b) 11 | if a < b: 12 | parent[b] = a 13 | else: 14 | parent[a] = b 15 | 16 | v, e = map(int, input().split()) 17 | parent = [0] * (v + 1) 18 | for i in range(1, v + 1): 19 | parent[i] = i 20 | 21 | edges = [] 22 | result = 0 23 | 24 | for _ in range(e): 25 | a, b, cost = map(int, input().split()) 26 | edges.append((cost, a, b)) 27 | 28 | edges.sort() 29 | 30 | # Check in order of low-cost edges. 31 | for edge in edges: 32 | cost, a, b = edge 33 | # If there will be no cycle, union. 34 | if find_parent(parent, a) != find_parent(parent, b): 35 | union_parent(parent, a, b) 36 | result += cost 37 | 38 | print(result) 39 | 40 | ''' 41 | [Input Example 1] 42 | 7 9 43 | 1 2 29 44 | 1 5 75 45 | 2 3 35 46 | 2 6 34 47 | 3 4 7 48 | 4 6 23 49 | 4 7 13 50 | 5 6 53 51 | 6 7 25 52 | [Output Example 1] 53 | 159 54 | ''' 55 | -------------------------------------------------------------------------------- /Graph/topology_sort.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | v, e = map(int, input().split()) 4 | indegree = [0] * (v + 1) 5 | graph = [[] for i in range(v + 1)] 6 | 7 | for _ in range(e): 8 | a, b = map(int, input().split()) 9 | graph[a].append(b) 10 | indegree[b] += 1 11 | 12 | ''' Topology Sort ''' 13 | def topology_sort(): 14 | result = [] 15 | q = deque() 16 | 17 | for i in range(1, v + 1): 18 | if indegree[i] == 0: 19 | q.append(i) 20 | 21 | while q: 22 | now = q.popleft() 23 | result.append(now) 24 | for i in graph[now]: 25 | indegree[i] -= 1 26 | if indegree[i] == 0: 27 | q.append(i) 28 | 29 | for i in result: 30 | print(i, end=' ') 31 | 32 | topology_sort() 33 | 34 | ''' 35 | [Input Example 1] 36 | 7 8 37 | 1 2 38 | 1 5 39 | 2 3 40 | 2 6 41 | 3 4 42 | 4 7 43 | 5 6 44 | 6 4 45 | [Output Example 1] 46 | 1 2 5 3 6 4 7 47 | ''' 48 | -------------------------------------------------------------------------------- /Miscellaneous/fenwick_tree.py: -------------------------------------------------------------------------------- 1 | n = 5 2 | tree = [0] * (n + 1) 3 | 4 | ''' Fenwick Tree (Binary Indexed Tree) ''' 5 | def update(i, dif): 6 | global n 7 | while i <= n: 8 | tree[i] += dif 9 | i += (i & -i) 10 | 11 | def update_to(i, to): 12 | update(i, to - interval_sum(i, i)) 13 | 14 | def get_sum(i): 15 | res = 0 16 | while i > 0: 17 | res += tree[i] 18 | i -= (i & -i) 19 | return res 20 | 21 | def interval_sum(start, end): 22 | return get_sum(end) - get_sum(start - 1) 23 | 24 | # Set all the data input 25 | update_to(1, 1) 26 | update_to(2, 2) 27 | update_to(3, 3) 28 | update_to(4, 4) 29 | update_to(5, 5) 30 | # Interval sum from index 2 to index 5. 31 | print(interval_sum(2, 5)) 32 | # Update index 3. 33 | update(3, -2) 34 | # Interval sum from index 2 to index 5. 35 | print(interval_sum(2, 5)) 36 | # Update index 5. 37 | update(5, 2) 38 | # Interval sum from index 2 to index 5. 39 | print(interval_sum(2, 5)) 40 | # Interval sum from index 1 to index 5. 41 | print(interval_sum(1, 5)) 42 | -------------------------------------------------------------------------------- /Miscellaneous/number_of_intervals_whose_sum_is_M.py: -------------------------------------------------------------------------------- 1 | ''' Find the number of intervals whose sum is M (using the two-pointer method). ''' 2 | n = 5 3 | m = 5 4 | data = [1, 2, 3, 2, 5] 5 | 6 | count = 0 7 | interval_sum = 0 8 | end = 0 9 | 10 | # move 'start' pointer to the right. 11 | for start in range(n): 12 | # move 'end' pointer to the right. 13 | while interval_sum < m and end < n: 14 | interval_sum += data[end] 15 | end += 1 16 | # If the sum of interval is 'm', count the number. 17 | if interval_sum == m: 18 | count += 1 19 | interval_sum -= data[start] 20 | 21 | print(count) 22 | -------------------------------------------------------------------------------- /Miscellaneous/prefix_sum.py: -------------------------------------------------------------------------------- 1 | n = 5 2 | data = [10, 20, 30, 40, 50] 3 | 4 | ''' Make prefix sum array ''' 5 | summary = 0 6 | prefix_sum = [0] 7 | for i in data: 8 | summary += i 9 | prefix_sum.append(summary) 10 | 11 | ''' Get interval sum ''' 12 | left = 2 13 | right = 4 14 | print(prefix_sum[right] - prefix_sum[left - 1]) 15 | -------------------------------------------------------------------------------- /Miscellaneous/rotate_a_matrix_by_90_degree.py: -------------------------------------------------------------------------------- 1 | a = [ 2 | [1, 2, 3, 4], 3 | [5, 6, 7, 8], 4 | [9, 10, 11, 12] 5 | ] 6 | 7 | ''' Rotate a matrix by 90 degree ''' 8 | def rotate_a_matrix_by_90_degree(a): 9 | row_length = len(a) 10 | column_length = len(a[0]) 11 | 12 | res = [[0] * row_length for _ in range(column_length)] 13 | for r in range(row_length): 14 | for c in range(column_length): 15 | res[c][row_length - 1 - r] = a[r][c] 16 | 17 | return res 18 | 19 | print(rotate_a_matrix_by_90_degree(a)) 20 | -------------------------------------------------------------------------------- /Number Theory/find_all_divisors_of_a_number.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | ''' Find all divisors of a number ''' 4 | def find_all_divisors_of_a_number(x): 5 | result = [] 6 | for i in range(1, int(math.sqrt(x)) + 1): 7 | if x % i == 0: 8 | result.append(i) 9 | if i * i != x: 10 | result.append(x // i) 11 | return result 12 | 13 | print(find_all_divisors_of_a_number(12)) # [1, 12, 2, 6, 3, 4] 14 | -------------------------------------------------------------------------------- /Number Theory/gcd.py: -------------------------------------------------------------------------------- 1 | x = 24 2 | y = 32 3 | 4 | ''' GCD (Greatest Common Divisor) ''' 5 | def gcd(a, b): 6 | mod = a % b 7 | while mod > 0: 8 | a = b 9 | b = mod 10 | mod = a % b 11 | return b 12 | 13 | print(gcd(x, y)) 14 | -------------------------------------------------------------------------------- /Number Theory/is_prime_number.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | ''' Check if a number is prime ''' 4 | def is_prime_number(x): 5 | for i in range(2, int(math.sqrt(x)) + 1): 6 | if x % i == 0: 7 | return False 8 | return True 9 | 10 | print(is_prime_number(4)) # False 11 | print(is_prime_number(7)) # True 12 | -------------------------------------------------------------------------------- /Number Theory/lcm.py: -------------------------------------------------------------------------------- 1 | x = 24 2 | y = 32 3 | 4 | ''' GCD (Greatest Common Divisor) ''' 5 | def gcd(a, b): 6 | mod = a % b 7 | while mod > 0: 8 | a = b 9 | b = mod 10 | mod = a % b 11 | return b 12 | 13 | ''' LCM (Least Common Multiple) ''' 14 | def lcm(a, b): 15 | return a * b // gcd(a, b) 16 | 17 | print(lcm(x, y)) 18 | -------------------------------------------------------------------------------- /Number Theory/prime_factorization.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | ''' Get all the prime factors ''' 4 | def prime_factorization(x): 5 | result = [] 6 | for i in range(2, int(math.sqrt(x)) + 1): 7 | # If 'i' is a divisor of 'x', 8 | if x % i == 0: 9 | # Count how many times 'i' can divide 'x' consecutively. 10 | count = 0 11 | while x % i == 0: 12 | count += 1 13 | x //= i 14 | result.append((i, count)) 15 | if x > 1: 16 | result.append((x, 1)) 17 | return result 18 | 19 | # Note: 1 is neither a prime number (소수) nor a composite number (합성수). 20 | print(prime_factorization(32)) # [(2, 5)] 21 | print(prime_factorization(45)) # [(3, 2), (5, 1)] 22 | print(prime_factorization(75)) # [(3, 1), (5, 2)] 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Python Competitive Programming Team Notes 2 | 3 | * This repository is a python library for PS(Problem-Solving) Competition. 4 | * When you need an implementation of a specific algorithm, please let me know. 5 | * 알고리즘 대회를 위한 파이썬 (Python) 소스코드 저장소입니다. 6 | 7 | ## Contents 8 | 9 | ### Sorting 10 | 11 | * [Selection Sort](/Sorting/selection_sort.py) 12 | * [Insertion Sort](/Sorting/insertion_sort.py) 13 | * [Quick Sort](/Sorting/quick_sort.py) 14 | * [Counting Sort](/Sorting/counting_sort.py) 15 | * [Python Sort Library](/Sorting/python_sort_library.py) 16 | 17 | ### Searching 18 | 19 | * [Binary Search](/Searching/binary_search.py) 20 | * [Python Binary Search Library](/Searching/python_binary_search_library.py) 21 | * [Count the number of frequencies of elements whose value is between \[left, right\] in a sorted array](/Searching/count_the_number_of_frequencies_in_a_sorted_array.py) 22 | * DFS 23 | * BFS 24 | * [Find the number of connected components](/Searching/find_the_number_of_connected_components.py) 25 | * [DFS & BFS Examples 1](/Searching/dfs_and_bfs_example_1.py) 26 | 27 | ### Graph 28 | 29 | * [Dijkstra Shortest Path](/Graph/dijkstra_shortest_path.py) 30 | * [Minimum Spanning Tree (MST)](/Graph/minimum_spanning_tree.py) 31 | * [Topology Sort](/Graph/topology_sort.py) 32 | * Floyd–Warshall algorithm 33 | * Bipartite Matching 34 | 35 | ### Data Structure 36 | 37 | * [Disjoint-Set (Union-Find)](/Data%20Structure/disjoint_set.py) 38 | * Tree 39 | * Line 40 | * Plane 41 | 42 | ### String 43 | 44 | * Rabin-Karp 45 | * KMP 46 | * Trie 47 | 48 | ### Dynamic Programming 49 | 50 | * Tiling Problem 51 | * 0-1 Knapsack Problem 52 | * LIS (Longest Increasing Subsequence) 53 | * LCS (Longest Common Subsequence) 54 | * Matrix Chain Multiplication 55 | 56 | ### Geometry 57 | 58 | * [Number of intersection points of two lines in 1 dimension](/Geometry/number_of_intersection_points_of_two_lines_in_1_dimension.py) 59 | * CCW 60 | * Convex Hull 61 | * Polygon 62 | 63 | ### Probability Theory 64 | 65 | * Permutation 66 | * Combination 67 | 68 | ### Number Theory 69 | 70 | * [GCD (Greatest Common Divisor)](/Number%20Theory/gcd.py) 71 | * [LCM (Least Common Multiple)](/Number%20Theory/lcm.py) 72 | * [Check Prime Number](/Number%20Theory/is_prime_number.py) 73 | * [Find All Divisors](/Number%20Theory/find_all_divisors_of_a_number.py) 74 | * [Prime Factorization](/Number%20Theory/prime_factorization.py) 75 | * Sieve of Eratosthenes 76 | 77 | ### Signal Processing 78 | 79 | * FFT 80 | 81 | ### Miscellaneous 82 | 83 | * Two Pointers 84 | * [Number of intervals whose sum is M](/Miscellaneous/number_of_intervals_whose_sum_is_M.py) 85 | * Interval Sum 86 | * [Prefix Sum](/Miscellaneous/prefix_sum.py) 87 | * [Fenwick Tree (Binary Indexed Tree)](/Miscellaneous/fenwick_tree.py) 88 | * [Matrix Rotation](/Miscellaneous/rotate_a_matrix_by_90_degree.py) 89 | * Handling Recursion Limit 90 | -------------------------------------------------------------------------------- /Searching/binary_search.py: -------------------------------------------------------------------------------- 1 | ''' Binary Search (Iterative Method) ''' 2 | def binary_search(array, target, start, end): 3 | while start <= end: 4 | mid = (start + end) // 2 5 | # If the target is found, return the mid index. 6 | if array[mid] == target: 7 | return mid 8 | # If the value of the mid index is greater than the target, search the left part. 9 | elif array[mid] > target: 10 | end = mid - 1 11 | # If the value of the mid index is smaller than the target, search the right part. 12 | else: 13 | start = mid + 1 14 | return None 15 | 16 | n = 10 17 | target = 13 18 | array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] 19 | 20 | result = binary_search(array, target, 0, n - 1) 21 | if result == None: 22 | print(None) 23 | else: 24 | print(result + 1) 25 | -------------------------------------------------------------------------------- /Searching/count_the_number_of_frequencies_in_a_sorted_array.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left, bisect_right 2 | 3 | # Count the number of frequencies of elements whose value is between [left, right] in a sorted array. 4 | def count_the_number_of_frequencies_in_a_sorted_array(a, left_value, right_value): 5 | right_index = bisect_right(a, right_value) 6 | left_index = bisect_left(a, left_value) 7 | return right_index - left_index 8 | 9 | array = [1, 2, 3, 3, 3, 3, 4, 4, 8, 9] 10 | 11 | # Count the number of frequencies of elements whose value is 4 in a sorted array. 12 | print(count_the_number_of_frequencies_in_a_sorted_array(array, 4, 4)) 13 | 14 | # Count the number of frequencies of elements whose value is between [-1, 3] in a sorted array. 15 | print(count_the_number_of_frequencies_in_a_sorted_array(array, -1, 3)) 16 | -------------------------------------------------------------------------------- /Searching/dfs_and_bfs_example_1.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | ''' Depth First Search (DFS) ''' 4 | def dfs(x): 5 | print(x, end=' ') 6 | visited[x] = True 7 | for y in graph[x]: 8 | if not(visited[y]): 9 | dfs(y) 10 | 11 | ''' Breadth First Search (BFS) ''' 12 | def bfs(x): 13 | q = deque([x]) 14 | visited[x] = True 15 | while q: 16 | x = q.popleft() 17 | print(x, end=' ') 18 | for y in graph[x]: 19 | if not visited[y]: 20 | q.append(y) 21 | visited[y] = True 22 | 23 | n, m, start = map(int, input().split()) 24 | graph = [[] for _ in range(n + 1)] 25 | for _ in range(m): 26 | x, y = map(int, input().split()) 27 | graph[x].append(y) 28 | graph[y].append(x) 29 | 30 | for e in graph: 31 | e.sort() 32 | 33 | visited = [False] * (n + 1) 34 | dfs(start) 35 | print() 36 | visited = [False] * (n + 1) 37 | bfs(start) 38 | 39 | ''' 40 | [Input Example 1] 41 | 4 5 1 42 | 1 2 43 | 1 3 44 | 1 4 45 | 2 4 46 | 3 4 47 | [Output Example 1] 48 | 1 2 4 3 49 | 1 2 3 4 50 | ''' 51 | -------------------------------------------------------------------------------- /Searching/find_the_number_of_connected_components.py: -------------------------------------------------------------------------------- 1 | ''' Find the number of connected components ''' 2 | from collections import deque 3 | 4 | n = 15 5 | m = 14 6 | data = [ 7 | '00000111100000', 8 | '11111101111110', 9 | '11011101101110', 10 | '11011101100000', 11 | '11011111111111', 12 | '11011111111100', 13 | '11000000011111', 14 | '01111111111111', 15 | '00000000011111', 16 | '01111111111000', 17 | '00011111111000', 18 | '00000001111000', 19 | '11111111110011', 20 | '11100011111111', 21 | '11100011111111' 22 | ] 23 | 24 | visited = [[False] * m for _ in range(n)] 25 | dx = [-1, 1, 0, 0] 26 | dy = [0, 0, -1, 1] 27 | 28 | def bfs(x, y): 29 | queue = deque([(x, y)]) 30 | visited[x][y] = True 31 | while queue: 32 | x, y = queue.popleft() 33 | for i in range(4): 34 | nx = x + dx[i] 35 | ny = y + dy[i] 36 | if nx < 0 or ny < 0 or nx >= n or ny >= m: 37 | continue 38 | if data[x][y] == '0' and not visited[nx][ny]: 39 | visited[nx][ny] = True 40 | queue.append((nx, ny)) 41 | 42 | result = 0 43 | for i in range(n): 44 | for j in range(m): 45 | # Find the number of connected components consisting only of '0'. 46 | if data[i][j] == '0' and not visited[i][j]: 47 | bfs(i, j) 48 | result += 1 49 | 50 | print(result) 51 | -------------------------------------------------------------------------------- /Searching/python_binary_search_library.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left, bisect_right 2 | 3 | # Locate the leftmost value exactly equal to x 4 | def index_of_x(a, x): 5 | i = bisect_left(a, x) 6 | if i != len(a) and a[i] == x: 7 | return i 8 | return None 9 | 10 | # Locate the rightmost value less than x 11 | def index_of_less_than_x(a, x): 12 | i = bisect_left(a, x) 13 | if i: 14 | return i - 1 15 | return None 16 | 17 | # Locate the rightmost value less than or equal to x 18 | def index_of_less_or_equal_than_x(a, x): 19 | i = bisect_right(a, x) 20 | if i: 21 | return i - 1 22 | return None 23 | 24 | # Locate the leftmost value greater than x 25 | def index_of_greater_than_x(a, x): 26 | i = bisect_right(a, x) 27 | if i != len(a): 28 | return i 29 | return None 30 | 31 | # Locate the leftmost value greater than or equal to x 32 | def index_of_greater_equal_than_x(a, x): 33 | i = bisect_left(a, x) 34 | if i != len(a): 35 | return i 36 | return None 37 | 38 | n = 10 39 | target = 13 40 | array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] 41 | 42 | result = index_of_x(array, target) 43 | if result == None: 44 | print(None) 45 | else: 46 | print(result + 1) 47 | -------------------------------------------------------------------------------- /Sorting/counting_sort.py: -------------------------------------------------------------------------------- 1 | n = 5 2 | data = [8, 5, 4, 7, 2] 3 | 4 | ''' Counting Sort ''' 5 | # Initialize a list whose size is greater than a range of all values. 6 | count = [0] * (max(data) + 1) 7 | 8 | for i in range(n): 9 | count[data[i]] += 1 # Increase the value in the index. 10 | 11 | for i in range(len(count)): # Check the sort information recorded on the list. 12 | for j in range(count[i]): 13 | print(i) # Print each index as many times as it appears. 14 | -------------------------------------------------------------------------------- /Sorting/insertion_sort.py: -------------------------------------------------------------------------------- 1 | n = 5 2 | data = [8, 5, 4, 7, 2] 3 | 4 | ''' Insertion Sort ''' 5 | for i in range(1, n): 6 | for j in range(i, 0, -1): # The variable j decreases from i to 1. 7 | if data[j - 1] > data[j]: # Move forward. 8 | data[j - 1], data[j] = data[j], data[j - 1] # Swap. 9 | else: # When reaching a smaller value, then stop. 10 | break 11 | 12 | for x in data: 13 | print(x) 14 | -------------------------------------------------------------------------------- /Sorting/python_sort_library.py: -------------------------------------------------------------------------------- 1 | n = 5 2 | 3 | ''' Python Sort Library (Basic) ''' 4 | data = [8, 5, 4, 7, 2] 5 | data.sort() 6 | 7 | for x in data: 8 | print(x) 9 | 10 | print("---------------") 11 | 12 | ''' Python Sort Library (Based on a key) ''' 13 | data = [(25, 'Na'), (20, 'Kim'), (23, 'Seo'), (28, 'Park'), (20, 'Ahn')] 14 | data.sort(key=lambda x: x[0]) # Stable Sort (When using a key) 15 | 16 | for x in data: 17 | print(x) 18 | 19 | print("---------------") 20 | 21 | ''' Python Sort Library ''' 22 | data = [(25, 'Na'), (20, 'Kim'), (23, 'Seo'), (28, 'Park'), (20, 'Ahn')] 23 | data.sort() # Non-stable Sort (When not using a key) 24 | 25 | for x in data: 26 | print(x) 27 | 28 | print("---------------") 29 | -------------------------------------------------------------------------------- /Sorting/quick_sort.py: -------------------------------------------------------------------------------- 1 | n = 5 2 | data = [8, 5, 4, 7, 2] 3 | 4 | ''' Quick Sort ''' 5 | def quick_sort(start, end): 6 | if start >= end: # If the subarray size is 1, exit the function. 7 | return 8 | pivot = start # The pivot is the first element of the subarray. 9 | left = start + 1 10 | right = end 11 | while left <= right: 12 | # Until finding an element bigger than the pivot, 13 | while left <= end and data[left] <= data[pivot]: 14 | left += 1 15 | # Until finding an element smaller than the pivot, 16 | while right > start and data[right] >= data[pivot]: 17 | right -= 1 18 | if left > right: # If two elements miss each other, 19 | data[right], data[pivot] = data[pivot], data[right] 20 | else: # If two elements don't miss each other, 21 | data[left], data[right] = data[right], data[left] 22 | # Sort the left part and right part respectively. 23 | quick_sort(start, right - 1) 24 | quick_sort(right + 1, end) 25 | 26 | quick_sort(0, n - 1) 27 | 28 | for x in data: 29 | print(x) 30 | -------------------------------------------------------------------------------- /Sorting/selection_sort.py: -------------------------------------------------------------------------------- 1 | n = 5 2 | data = [8, 5, 4, 7, 2] 3 | 4 | ''' Selection Sort ''' 5 | for i in range(n): 6 | min_index = i # The index of the minimum value. 7 | for j in range(i + 1, n): 8 | if data[min_index] > data[j]: 9 | min_index = j 10 | data[i], data[min_index] = data[min_index], data[i] # Swap. 11 | 12 | for x in data: 13 | print(x) 14 | --------------------------------------------------------------------------------