#include<iostream>
using namespace std;
int selectSort(int *a,int length);
int bubbleSort(int* a, int length);
int insertSort(int* a, int length);
void swap(int* a, int b, int c);
int main()
{
int a[] = { 0,2,4,7,8,5,9,1,3,6 };
int length = sizeof(a) / sizeof(a[0]);
int j = insertSort(a, length);
for(int i = 0;i<length;i++)cout << a[i]<<"\t";
return 0;
}
int selectSort(int* a,int length)
{
if (a == nullptr || length < 2)
{
return -1;
}
for (int i = 0; i < length; i++)
{
int minNumIndex = i;
for (int j = i + 1; j < length; j++)
{
minNumIndex = a[j] < a[minNumIndex] ? j : minNumIndex;
}
if (minNumIndex != i)swap(a, i, minNumIndex);
}
return 0;
}
int bubbleSort(int* a, int length)
{
if (a == nullptr || length < 2)
{
return -1;
}
for (int i = length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (a[j] > a[j + 1])
{
swap(a, j, j + 1);
}
}
}
return 0;
}
int insertSort(int* a, int length)
{
if (a == nullptr || length < 2)
{
return -1;
}
for (int i = 1; i < length; i++)
{
for (int j = i; j > 0 && a[j] < a[j - 1]; j--)
{
swap(a, j, j - 1);
}
}
return 0;
}
void swap(int* a,int b, int c)
{
a[b] = a[b] ^ a[c];
a[c] = a[b] ^ a[c];
a[b] = a[b] ^ a[c];
}
|