C language to achieve bubble sort, hill sorting and other algorithms examples _c language

Source: Internet
Author: User
Tags array length

Implement the following sort

Insert sort O (n^2)

Bubble sort O (n^2)

Select Sort O (n^2)

Quick Sort O (n log n)

Heap sort O (n log n)

Merge sort O (n log n)

Hill sort O (n^1.25)

1. Insert sort O (n^2)

In general, the insertion sort is implemented on an array using In-place. The specific algorithm is described as follows:
⒈ starting with the first element, the element can be considered to have been sorted
⒉ takes out the next element and scans the sequence of elements that are already sorted from the back forward
⒊ if the element (sorted) is greater than the new element, move the element to the next position
⒋ Repeat step 3 until you find the location of the sorted element less than or equal to the new element
⒌ inserts a new element into the next location
⒍ Repeat steps 2~5
If the cost of comparison operations is greater than the exchange operation, the binary lookup method can be used to reduce the number of comparison operations. The algorithm can be considered a variant of the insertion sort, called a binary lookup sort.

Copy Code code as follows:

void Insert_sort (int* array,unsignedint N) {
int i,j;
int temp;
for (i=1;i<n;i++) {
temp=* (Array+i);
For (j=i;j>0&&* (array+j-1) >temp;j--) {
* (ARRAY+J) =* (array+j-1);
}
* (ARRAY+J) =temp;
}
}

2. Bubble sort O (n^2)

The bubble sort algorithm works as follows:
Compare the adjacent elements. If the first one is bigger than the second one, swap them both.
Do the same work for each pair of adjacent elements, from the first pair to the end of the last couple. At this point, the final element should be the largest number.
Repeat the above steps for all elements except the last one.
Continue to repeat the previous steps for less and fewer elements until no pair of digits need to be compared.

Copy Code code as follows:

#include <stdio.h>
#defineSIZE8
void Bublle_sort (int a[],int n) {//n number of elements in array a
int i,j,temp;
for (j=0;j<n-1;j++)
for (i=0;i<n-1-j;i++)
if (A[i]>a[i+1]) {//array element size in ascending order
Temp=a[i];
A[I]=A[I+1];
A[i+1]=temp;
}
}
int main () {
int number[size]={95,45,15,78,84,51,24,12};
int i;
Bublle_sort (number,size);
for (i=0;i<size;i++) {
printf ("%d", number[i]);
}
printf ("\ n");
}

3. Select Sort O (n^2)

Copy Code code as follows:

void Select_sort (int * A, int n) {
Register int i, j, Min, T;
For (i =0 i < n-1 i + +) {
min = i; Find Minimum value
for (j = i +1; j < N; j + +)
if (A[min] > A[j])
min = j; Exchange
if (min!= i) {
t = a[min];
A[min] = A[i];
A[i] = t;
}
}
}

4. Quick Sort O (n log n)

Copy Code code as follows:

void QuickSort (int a[],int numsize) {//a is an array of integers, numsize is the number of elements
int i=0,j=numsize-1;
int val=a[0];//Specify reference value val size
if (numsize>1) {//Ensure that the array length is at least 2, otherwise there is no need to sort
while (i<j{//Loop End condition
for (; j>i;j--)//From backward search for elements smaller than Val, find and fill in a[i] and jump out of the loop
if (a[j]<val) {
A[i]=a[j];break;
}
for (; i<j;i++)//From after the search for a larger than Val elements, find and fill in a[j] and jump out of the loop
if (a[i]>val) {
A[j]=a[i];break;
}
}
a[i]=val;//put the number saved in Val into A[i]
QuickSort (a,i);//recursion, order of number of first I
QuickSort (a+i+1,numsize-1-i)//i+1 to numsize the number of numsize-1-i sorted
}
}

5. Heap sort O (n log n)
The N-keyword sequence kl,k2,...,kn is called (HEAP) if and only if the sequence satisfies the following properties (referred to as heap properties):
(1) ki<=k (2i) and Ki<=k (2i+1) (1≤i≤n), of course, this is a small Gan, Dagen is replaced by the >= number. K (i) is the Zoozi node of the two-fork tree, and K (2i) is the right child node.
If the vector stored by this sequence is R[1..N] as a storage structure of a complete binary tree, the heap is essentially a complete binary tree that satisfies the following properties: None of the key words in the tree is greater than (or less than) the key word for its left and right children (if any).

Copy Code code as follows:

The array is the heap array to be adjusted, I is the position of the array element to be adjusted, and the nlength is the length of the array
This function is: to build a large heap based on array arrays
void Heapadjust (int array[], int i, int nlength)
{
int nchild;
int ntemp;
for (ntemp = array[i]; 2 * i + 1 < nlength; i = nchild)
{
The position of the =2* (parent node position) + 1
Nchild = 2 * i + 1;
To get the larger node in the sub node.
if (Nchild < nLength-1 && array[nchild + 1] > Array[nchild])
++nchild;
If the larger child node is larger than the parent node, move the larger child node up and replace its parent node.
if (Ntemp < Array[nchild])
{
Array[i] = Array[nchild];
Array[nchild]= ntemp;
}
Else
Otherwise exit the loop
Break
}
}

Heap Sorting algorithm
void heapsort (int array[],int length)
{
int tmp;
Adjusts the first half of the sequence, and after it is adjusted, is the largest element of the sequence.
Length/2-1 is the first non-leaf node where "/" is divisible
for (int i = floor (length-1)/2; I >= 0; i.)
Heapadjust (array, I, length);
Adjusts the sequence from the last element, constantly narrowing the adjustment until the first element
for (int i = length-1 i > 0; i.)
{
Swap the first element with the current last element,
To ensure that the elements of the current last position are the largest in the present sequence.
Swap (&array[0], &array[i]);
TMP = Array[i];
Array[i] = array[0];
ARRAY[0] = tmp;
Constantly narrowing the range of adjustment heap to ensure that the first element is the maximum value of the current sequence, each time it is adjusted
Heapadjust (array, 0, i);
}
}

6. Merge sort O (n log n)

The ordered Subsequence is merged to obtain a fully ordered sequence, that is, the sequence of each subsequence is ordered, and then the sequence between the subsequence segments is ordered. If the two ordered table is merged into an ordered table, it is called two-way merge.

Copy Code code as follows:

Merge operation
void Merge (int sourcearr[], int targetarr[], int startIndex, int midindex, int endindex)
{
int I, j, K;
for (i = midindex+1, j = startIndex; StartIndex <= midindex && i <= endindex; j +)
{
if (Sourcearr[startindex] < sourcearr[i])
{
TARGETARR[J] = sourcearr[startindex++];
}
Else
{
TARGETARR[J] = sourcearr[i++];
}
}

if (StartIndex <= midindex)
{
for (k = 0; k <= midindex-startindex; k++)
{
TARGETARR[J+K] = sourcearr[startindex+k];
}
}

if (i <= endindex)
{
for (k = 0; k <= endindex-i; k++)
{
TARGETARR[J+K] = sourcearr[i+k];
}
}
}
Internal use of recursion, spatial complexity of N+LOGN
void mergesort (int sourcearr[], int targetarr[], int startIndex, int endindex)
{
int midindex;
int temparr[100]; This size changes according to requirements
if (StartIndex = = endindex)
{
Targetarr[startindex] = Sourcearr[startindex];
}
Else
{
Midindex = (StartIndex + endindex)/2;
MergeSort (Sourcearr, Temparr, StartIndex, Midindex);
MergeSort (Sourcearr, Temparr, midindex+1, endindex);
Merge (Temparr, Targetarr,startindex, Midindex, endindex);
}
}

Call
int _tmain (int argc, _tchar* argv[])
{
int a[8]={50,10,20,30,70,40,80,60};
int b[8];
MergeSort (A, B, 0, 7);
for (int i = 0; i < sizeof (a)/sizeof (*A); i++)
cout << b[i] << ';
cout << Endl;
System ("pause");
return 0;
}

7. Hill sort O (n^1.25)
First, take an integer d1 less than n as the first increment, dividing the entire record of the file into D1 groups. All records with a multiple distance of D1 are placed in the same group. A direct insertion sort is performed within each group, and then the second increment d2<d1 repeats the grouping and sorting above until the incremental dt=1 (DT<DT-L<...<D2<D1) is taken, where all records are placed in the same group for direct insertion sort.

Copy Code code as follows:

void Shellsort (int a[], int n) {
int d, I, J, temp;
for (d = n/2;d >= 1;d = D/2) {
for (i = D; i < n;i++) {
temp = A[i];
for (j = i-d; (j >= 0) && (a[j] > Temp); j = j-d) {
A[j + d] = a[j];
}
A[j + d] = temp;
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.