Common data structures and algorithms
Sort (bubble insert merge selected heapsort fast Hill base)
Sort independent of the initial state of the sort of instability in
Formulas: Greek election heap quick return basis remains unstable heap election
Bubble Time: O (N ^ 2) Space: O (1)
Ideas: Find the maximum switching element placed the forefront.
void bubble_sort(int arr[],int len)
{
for(int i=0;i<len;i++)
for(int j=0;j<len-i-1;j++)//
{
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
Quick drain <divide and conquer> Time: O (nlogn) Space: O (logn)
Idea: find a random element as a reference, than its large numbers on the back, than it is a small figure on the front
int Partition(int A[],int low,int high)
{
int key=A[low];
while(low<high)
{
while(low<high&&A[high]>=key)
{
--high;
}
A[low]=A[high];
while(low<high &&A[low]<=key)
{
++low;
}
A[high]=A[low];
}
A[low]=key;
return low;
}
void QuickSort(int A[],int low,int high)
{
if(low<high)
{
int middle=Partition(A,low,high);
QuickSort(A,low,middle-1);
QuickSort(A,middle+1,high);
}
}
Merge the time complexity of O (nlogn) space complexity of O (n)
Thinking: into individual sorted sequence, then the combined sequence
void mergesort(int a[],int first,int last,int temp)//递归排序
{
if(first<last)
{
int mid=(first+last)/2;
mergesort(a,first,mid,temp);
mergesort(a,mid+1,last,temp);
mergearray(a,first,mid,last,temp);
}
}
void mergearray(int a[],int first,int mid,int last,int temp[])//合并序列
{
int i=first;
int j=mid+1;
int k=0;
while(i<=mid&&j<=last)
{
if(a[i]<=a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=mid)
temp[k++]=a[i++];//当j>last时,序列最后的数字合并
while(j<=n)
temp[k++]=a[j++];
}
Heap sort time complexity of O (nlogn) space complexity of O (1)
Thinking: collating sequence to be configured into a large pile top, at this time, the maximum value of the root node is the top of the stack of the entire sequence. To be exchanged with the last element on the end of this time the maximum value. The remaining n-1 th element of a stack is reconfigured, it would receive the next smallest value of n elements.