About fast, bubbling, select, insert, etc. sort, I implemented in code can run successfully.
In addition to sorting paper for several swap function, also described by the assembler code analysis, maximum efficiency swap1 function.
#include<iostream>
#include <cstdio>
/ * Swap function * /
void swap1 (A int *, int * B) {
int * tmp = A;
* = A * B;
* B = tmp;
}
/ **
* swap2 and swap3 for the same variable, cause this variable to 0
* Because two pointers point to the same variable.
* /
Void swap2 (A int *, int * B)
{
* A ^ = A * B *;
* B = ^ * A * B; // * B * A ^ B ^ * -> * A
* A * = * B ^ A; // * A * A ^ B ^ * -> * B
}
void swap3(int *a,int *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
void swap3(int &a,int &b){
printf("swap3:%d,%d\n",a,b);
a = a + b;
b = a - b;
a = a - b;
printf("swap3 end:%d,%d\n",a,b);
}
/ * Quicksort * /
// instability, the time complexity of O (logN) - O (N ) space complexity O (. 1)
void quicksort (A int *, int Low, High int)
{
int i = low;
int j = high;
int key = a[low];
if(low >= high){
return;
}
while(low < high){
while(low<high && key <= a[high]){
--high;
}
IF (Key> A [High]) {
swap2 (& A [Low], & [High] A); // exchanged with the least significant bit position of the highest available data
++ Low;
}
while(low <high && key >= a[low] ){
++low;
}
if(key < a[low]){
swap2(&a[low], &a[high]);
--high;
}
}
quicksort(a,i,low-1);
quicksort(a,low+1,j);
}
/ * Bubble sort * /
// stable worst O (N ^ 2) is preferably O (N) space complexity O (. 1)
void maopaoSort (A int *, int size)
{
int J, I;
for ( 0 = I; I <size; I ++) {
for (J = I +. 1; J <size; J ++) {
IF (A [J]> A [I]) {
swap2 (& A [J], A & [I]);
}
}
}
}
/*插入排序*/
//稳定,最坏O(N^2) 最好O(N)
void insertSort(int nums[],int size)
{
int i,j;
for(i=1;i<size;++i){
int n = nums[i];
j = i-1;
while(j>=0&&n>=nums[j]){
nums[j+1] = nums[j];
--j;
}
nums[j+1] = n;
}
}
/ * * Selection Sort /
// unstable worst O (N ^ 2) is preferably O (N)
void SelectSort (the nums int *, int size)
{
int I = 0, J = 0;
int index = 0;
for (I = 0; I <-size. 1; I ++) {
index = I;
for (I = J +. 1; J <size; J ++) {
IF (the nums [index] <the nums [J]) {
index = J;
}
}
IF (index = I!)
swap3 (the nums [index], the nums [I]); // use the overloaded reference type
}
}
void show(int *a,int size)
{
std::cout<<"show:"<<std::endl;
for(int i=0;i<size;++i){
std::cout<<a[i]<<" ";
}
std::cout<<std::endl;
}
int main()
{
int arra[] = {100,2,10,11,9,-1000};
int size = sizeof(arra)/sizeof(arra[0]);
printf("sort start:\n");
show(arra, size);
selectSort(arra,size);
printf("sort end:\n");
show(arra, size);
}