• No results found

sorting.docx

N/A
N/A
Protected

Academic year: 2020

Share "sorting.docx"

Copied!
10
0
0

Loading.... (view fulltext now)

Full text

(1)

OBJECT: understanding and implementing sorting

In Algorithm Design, Sorting is an important part. Different algorithm use the sorting algorithm. Some Interesting sorting algorithm are include here: Bubble Sort, Heap Sort, Quick Sort,

Counting Sort, Selection Sort, Insertion Sort etc.

In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important to optimizing the use of other algorithms (such as search and merge algorithms) that require sorted lists to work correctly.

BUBBLE SORT:

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort.

Bubble sort has worst-case and average complexity both О(n2), where n is the number of items being sorted. There exist many sorting algorithms with substantially better worst-case or average complexity of O(n log n). Even other О(n2) sorting algorithms, such as insertion sort, tend to have better performance than bubble sort. Therefore, bubble sort is not a practical sorting algorithm when n is large.

The only significant advantage that bubble sort has over most other implementations,

even quicksort, but not insertion sort, is that the ability to detect that the list is sorted efficiently is built into the algorithm. When the list is already sorted (best-case), the complexity of bubble sort is only O(n).

HEAP SORT:

heapsort is a comparison-based sorting algorithm. Heapsort can be thought of as an

improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum.[2]

(2)

QUICK SORT:

Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order.it is still a commonly used algorithm for sorting. When implemented well, it can be about two or three times faster than its main competitors, merge sort and heapsort.

Quicksort is a comparison sort, meaning that it can sort items of any type for which a "less-than" relation (formally, a total order) is defined. In efficient implementations it is not a stable sort, meaning that the relative order of equal sort items is not preserved. Quicksort can operate in-place on an array, requiring small additional amounts of memory to perform the sorting. Mathematical analysis of quicksort shows that, on average, the algorithm takes O(n log n) comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this behavior is rare.

INSERTION SORT:

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such

as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages:  Efficient for (quite) small data sets, much like other quadratic sorting algorithms

 More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such

as selection sort or bubble sort

 Adaptive, i.e., efficient for data sets that are already substantially sorted: the time

complexity is O(nk) when each element in the input is no more than k places away from its sorted position

 Stable; i.e., does not change the relative order of elements with equal keys  In-place; i.e., only requires a constant amount O(1) of additional memory space  Online; i.e., can sort a list as it receives it

MERGE SORT:

merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-basedsorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm

IMPLEMENTATION: #include <iostream>

#include <vector>

#include <queue>

using namespace std;

(3)

int tmp = data[i]; data[i] = data[j]; data[j] = tmp; }

void print(std::vector<int> const & data) {

std::vector<int>::const_iterator iter = data.begin();

for (; iter != data.end(); ++iter) {

cout << *iter << " "; }

if (data.size() > 0) {

cout << endl; }

}

int generateRandom(int low, int high);

void Shuffle(std::vector<int> & data) {

int length = data.size();

for (int i = 0; i < length-1; ++i) {

swap(data, i, generateRandom(i+1, length-1)); }

print(data); }

int generateRandom(int low, int high)

{

srand(low); int gen = 0;

gen = rand() % (high - low + 1) + low; return gen;

}

//useful for small lists, and for large lists where data is //already sorted

void BubbleSort(std::vector<int> & data) {

(4)

for (int i = 0; i < length; ++i) {

bool swapped = false;

for (int j = 0; j < length - (i+1); ++j) {

if (data[j] > data[j+1]) {

swap(data, j, j+1); swapped = true; }

}

if (!swapped) break; }

}

//useful for small lists and where swapping is expensive // does at most n swaps

void SelectionSort(std::vector<int> & data) {

int length = data.size();

for (int i = 0; i < length; ++i) {

int min = i;

for (int j = i+1; j < length; ++j) {

if (data[j] < data[min]) {

min = j; }

}

if (min != i) {

swap(data, i, min); }

} }

//useful for small and mostly sorted lists //expensive to move array elements

void InsertionSort(std::vector<int> & data) {

(5)

for (int i = 1; i < length; ++i) {

bool inplace = true; int j = 0;

for (; j < i; ++j) {

if (data[i] < data[j]) {

inplace = false; break;

} }

if (!inplace) {

int save = data[i]; for (int k = i; k > j; --k) {

data[k] = data[k-1]; }

data[j] = save; }

} }

void Merge(std::vector<int> & data, int lowl, int highl, int lowr, int highr); void MergeSort(std::vector<int> & data, int low, int high)

{

if (low >= high) {

return; }

int mid = low + (high-low)/2;

MergeSort(data, low, mid);

MergeSort(data, mid+1, high);

Merge(data, low, mid, mid+1, high); }

void Merge(std::vector<int> & data, int lowl, int highl, int lowr, int highr) {

(6)

std::vector<int> tmp;

while (lowl <= highl && lowr <= highr) {

if (data[lowl] < data[lowr]) {

tmp.push_back(data[lowl++]); }

else if (data[lowr] < data[lowl]) {

tmp.push_back(data[lowr++]); }

else {

tmp.push_back(data[lowl++]); tmp.push_back(data[lowr++]); }

}

while (lowl <= highl) {

tmp.push_back(data[lowl++]); }

while (lowr <= highr) {

tmp.push_back(data[lowr++]); }

std::vector<int>::const_iterator iter = tmp.begin();

for(; iter != tmp.end(); ++iter) {

data[tmp_low++] = *iter; }

}

intPartition(std::vector<int> & data, int low, int high); void QuickSort(std::vector<int> & data, int low, int high) {

if (low >= high) return;

int p = Partition(data, low, high);

(7)

}

intPartition(std::vector<int> & data, int low, int high) {

int p = low;

for (int i = p+1; i <= high; ++i) {

if (data[i] < data[p]) {

swap(data, i, p); if (i != p+1) {

swap(data, i, p+1); }

p = p + 1; }

}

return p; }

//O(kN) k is max number of digits

int findMaxDigits(std::vector<int> & data);

void PutInQueues(std::queue<int> q[], int qcount, std::vector<int> & data, int digit); void GetPartialSorted(std::queue<int> q[], int qcount, std::vector<int> & data);

void RadixSort(std::vector<int> & data) {

std::queue<int> q[10];

int maxDigits = findMaxDigits(data);

for (int i = 0; i < maxDigits; ++i) {

PutInQueues(q, 10, data, i+1);

data.clear();

GetPartialSorted(q, 10, data);

} }

int getDigitAt(int n, int digit);

void PutInQueues(std::queue<int> q[], int qcount, std::vector<int> & data, int digit) {

std::vector<int>::const_iterator iter = data.begin(); for(; iter != data.end(); ++iter)

{

(8)

q[qpos].push(*iter); }

}

int getDigitAt(int n, int digit) {

int dig = 0; while (digit--) {

dig = n % 10; n = n / 10; }

return dig; }

void GetPartialSorted(std::queue<int> q[], int qcount, std::vector<int> & data) {

for (int i = 0; i < qcount; ++i) {

if (q[i].size() > 0) {

int length = q[i].size(); while (length--) {

data.push_back(q[i].front()); q[i].pop();

} } } }

int numDigits(int n);

int findMaxDigits(std::vector<int> & data) {

std::vector<int>::const_iterator iter = data.begin(); int max = 0;

for (; iter != data.end(); ++iter) {

int numd = numDigits(*iter);

if (max < numd) {

max = numd; }

}

(9)

}

int numDigits(int n)

{

int count = 0; while(n != 0) {

n = n/10; ++count; }

return count; }

int main()

{

int a[] = {5, 6, 1, 2, 0, 8, -1, -2, 8, 0};

std::vector<int> data(a, a + sizeof(a)/sizeof(int));

//Bubble sort

BubbleSort(data); print(data);

//Selection sort

Shuffle(data); SelectionSort(data); print(data);

//Insertion sort

Shuffle(data); InsertionSort(data); print(data);

//Merge sort

Shuffle(data);

MergeSort(data, 0, data.size()-1); print(data);

//Quick sort

Shuffle(data);

QuickSort(data, 0, data.size()-1); print(data);

//Radix Sort

int b[] = {123, 6, 24, 4567, 45, 989834, 98, 23, 8, 0};

(10)

RadixSort(rdata); print(rdata);

References

Related documents

Insert the blood collection tube into the holder and onto the needle up to the guideline on the needle holder.. Remove sheath

Each patient in either the operated or turned down groups had a data set collected, which included patient related, cardiac related and operation related factors allowing

Dimitrova R, Gibson J, Turkel C, BONT-A CDH Study Group (2005) Botulinum toxin type A (BOTOX) for the prophylactic treatment of chronic daily headache: a randomized, double-

Finally, we provided a proof-of-concept by combining rep B and placI for expression of GFP gene in Shewanella , and followed by demonstrated expression of Mtr path- way as

 The total quantity of PAHs detected in the dry season are higher than those of the rainy season in marshy soil samples collected in Warri city in this study period. 

In mice subjected to PSNL, repeated once daily intrathecal injection of TAT-GESV (10 nmol i.t.) and MK-801 (5 nmol i.t.) across eight consecutive days elevated (A) mechanical

I understand that if the person or entity receiving this information is not a health plan or health care provider covered by the federal privacy regulations, the information may

the land. In the 1920s and 1930s, land grabbing was prevalent in agricultural regions in the Philippines. The refusal of tenants to vacate the land could be traced, in some