Search and sort 04, insert sort, search sort 04 insert

Source: Internet
Author: User

Search and sort 04, insert sort, search sort 04 insert

In the selection and sorting process, the elements in the array are traversed from the first element to find the minimum element after the elements are traversed, and the position is exchanged with the current traversal element, is a sort by the forward. In the insert sort, the elements in the array are traversed from the second element, compared with the previous element, and inserted to a previous position, is a sort from the back to the back.

 

A custom class maintains an array of int [] type. The constructor defines the length of the array and initializes it. It also provides methods for printing and inserting sorting.

    public class MyArray
    {
        private static int[] arr;
        private static Random r = new Random();
        public MyArray(int size)
        {
            arr = new int[size];
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = r.Next(10, 100);
            }
        }
// Insert sorting
        public void Sort()
        {
            int insert;
For (int I = 1; I <arr. Length; I ++) // traverse from the second element
            {
Insert = arr [I]; // insert the current traversal element into the temporary variable insert.
Int moveItem = I; // movieItem can be understood as a dynamic index with the initial position in the index of the current traversal element.
While (moveItem> 0 & arr [moveItem-1]> insert) // if the previous element is larger than the inserted element
                {
Arr [moveItem] = arr [moveItem-1]; // assign the preceding element to the following position, which is equivalent to moving one
MoveItem --; // move the dynamic index position one by one
                }
                arr[moveItem] = insert;
                Print();
            }
        }
// Print array elements
        public void Print()
        {
            foreach (var item in arr)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }
    }
The general process above is: starting from the second element in the array, first assign the current traversal element to a temporary variable, such as insert, the insert variable must be inserted to a position before the current traversal element. How can we determine the insertion position? Assuming that the moveItem variable is used to represent the final index location to be inserted, assign the index of the current traversal element to moveItem first, if the element at the moveItem-1 location is greater than insert, then move the element at the position of the moveItem-1 to a backward position and assign the index at the position of the moveItem-1 to moveItem. Is insert to the current position of the moveItem? Not necessarily. Continue to compare the elements in the previous position of the current moveItem with insert. If it is larger than insert, move the elements in the position one by one, and reset the value of moveItem until the loop is stopped. In this case, the value of moveItem is the position where insert is needed.

 

Client call.

    class Program
    {
        static void Main(string[] args)
        {
            MyArray myArray = new MyArray(8);
Console. WriteLine ("Before sorting :");
            myArray.Print();
Console. WriteLine ("sorted :");
            myArray.Sort();
            Console.ReadKey();
        }
    }

 

For insert sorting, n-1 iterations are performed when array elements are traversed in sequence. When the second element is inserted to a previous position, one iteration is performed, when the third element is inserted to a previous position, two iterations are performed ...... the Nth element carries out n-1 iterations. In terms of time complexity, ignore small items and constant items, and insert sorting is basically a square order written as O (n² ).

 

The "Search and sorting" series include:

Search and sorting 01, linear search, time complexity, algorithm search and sorting 02, half-lookup and sorting 03, select sorting search and sorting 04, insert sorting
Data search and sorting

Sequential search
Half Lookup
Multipart search
Direct Search

Insert sort
Hill sorting
Select sort
Quick sorting

Hill sorting code

* P = array pointer; n = number of array elements
Void Hill_arrangement (int * p, int n)
{Int I, gap, j, temp;
Gap = n/2;
While (gap> = 1)
{For (I = gap; I <n; I ++)
{Temp = * (p + I );
J = I;
While (j> = gap & * (p + j-gap)> temp)
{* (P + j) = * (p + j-gap );
J = j-gap;
* (P + j) = temp;
}
}
Gap = gap/2;
}
}

Code for the half-fold search of an ordered table (returns the subscript)

Int binarysearch (int * p, int n, int k)
{Int low = 0, up = n-1, mid;
While (low <= up)
{Mid = (low + up)/2;
If (k = * (p + mid) return mid;
Else if (k <* (p + mid) up = mid-1;
Else low = mid + 1;
}
Return-1;

}

Program query, sorting (ascending and descending), bubble sort, select sort, insert sort directly and binary insert sort

First, declare that the following program is not all written by me, and that you do not know what the binary insertion sorting is. I think it should be a binary query to find the sorted array !!!
Hope you are satisfied.

1. Sequential search

# Include <stdio. h>
Void main ()
{
Int a [10] = {1, 2, 4, 5, 6, 7, 8, 9, 10 };
Int I, x, y;
Printf ("Enter the number you want to search: \ n ");
Scanf ("% d", & x );
Y = 0; // indicates whether the table y = 1 is found. y = 0 indicates that the table y = 1 is not found.
For (I = 0; I <10; I ++) // loop, compare x with the elements in the array one by one
{
If (x = a [I]) // if x = a [I],
{
Y = 1; // convert y to 1, which indicates that
Printf ("The Number % d You Want to query is in the % d position \ n", x, I + 1); // output the relevant information
Break; // skip Loop
}
}
If (y = 0) printf ("the number you want to find cannot be found \ n"); // y = 0 indicates no
}

2. Sort (ascending and descending)

# Include <stdio. h>
Void main ()
{
Int a [5] = {};
Int I, j;
Int temp = 0;
For (I = 0; I <5; I ++)
{
Printf ("Enter the % d integer \ n", I + 1 );
Scanf ("% d", & a [I]);
}
For (I = 1; I <5; I ++)
{
For (j = 0; j <5-i; j ++)
{
If (a [j]> a [j + 1])
{
Temp = a [j];
A [j] = a [j + 1];
A [j + 1] = temp;
}
}
}
For (I = 0; I <5; I ++)
{
Printf ("sorted INTEGER: % d \ t", a [I]);
}
}
It is in ascending order .. If you want to change the order to descending order, you only need to swap the order of the size.

3. Bubble Sorting
# Include <stdio. h>
Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

4. Select sorting
# Include <stdio. h>
Void selectSort (int a [], int n)
{Int t, I, j, k;
For (I = 0; I <n-1; I ++)
{K = I;
For (j = I + 1; j <n; j ++)
If (a [j] <a [k])
K = j;
T = a [I];
A [I] = a [k];
A [k] = t;
}
}

... The remaining full text>

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.