Sorting (rearranging) data

Mathematics Machine Learning Artificial Intelligence Graph Data Algorithm Programming Digital Transformation Algorithm Clojure Navigation of this blog
Sorting (rearranging) data

Sorting (rearranging) data is the basis of algorithms. Sorting algorithms include the following.

Bubble sort, which compares adjacent values and repeats the process of replacing them; “Quick sort,” which determines a reference value, called a pipot, and repeats the process of dividing the data group into two groups, one above the reference value and the other below the reference value, to replace the elements; and “Merge sort” is a process of sorting and merging the data from the smallest unit.

Selective sorting, which involves finding the minimum value in the first and subsequent elements and exchanging it with the first element, and then finding the minimum value in the second and subsequent elements and exchanging it with the second element. If the order is reversed, reorder the elements insertion sort.

Heap sort” is a procedure that converts the original data into an ordered tree as shown below, compares the “children” and “parents” of the converted ordered tree, and if the parent is smaller than the child, the parent and child are exchanged for all combinations of nodes.

Heap-sorting has the feature of consuming less memory and can be processed at high speed.

These algorithms (especially the last binary tree) can be used as a base for more complex algorithms.

If you want to do a simple sort in a Clojure program, you can do it in the following way.

user=> (sort [3 1 2 4])
(1 2 3 4)

user=> (sort > (vals {:foo 5, :bar 2, :baz 10}))
(10 5 2)

;; do not do this, use sort-by instead
user=> (sort #(compare (last %1) (last %2)) {:b 1 :c 3 :a  2})
([:b 1] [:a 2] [:c 3])

;; like this:
user=> (sort-by last {:b 1 :c 3 :a 2})
([:b 1] [:a 2] [:c 3])

Basically, it uses the “sort” function, and if you put > after it, it will sort in descending order, if not, it will sort in ascending order, and the last sample “sort-by” shows sorting using a specific function (last, sort by the later part of the map data).

コメント

タイトルとURLをコピーしました