冒泡排序、选择排序、交换排序
1、冒泡排序bubble_sort
#include <iostream>
void bubble_sort(int *begin, int *end)
{
int *i, *j;
for(i = end; i >= begin; i--)
{
for(j = begin; j + 1 <= end; j++)
{
if(*j > *(j + 1))
{
int temp = *j;
*j = *(j + 1);
*(j + 1) = temp;
}
}
end --;
}
}
int main()
{
int data[] = {1,3,7,24,4,67,12,22,454};
bubble_sort(data + 0, data + 8);
for(int *i = data; i <= data + 8; i++)
std::cout << *i << " ";
return 0;
}
2、选择排序selection_sort
#include <iostream>
void selection_sort(int *begin, int *end)
{
for(int *i = begin; i < end; i ++)
{
int *k = i;
for(int *j = i + 1; j <= end; j ++)
if(*k > *j)
k = j;
if(k != i)
{
int temp = *k;
*k = *i ;
*i = temp;
}
}
}
int main()
{
int data[] = {1, 3, 12, 5, 13, 8, 0, 2, 7};
selection_sort(data + 0, data + 8);
for(int *i = data; i <= data + 8; i ++)
{
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
3、交换排序exchange_sort
void exchange_sort(int *begin, int *end)
{
for(int *i = begin; i < end; i ++)
for(int *j = i + 1; j <= end; j ++)
if(*i > *j)
{
int temp = *i;
*i = *j;
*j = temp;
}
}
int main()
{
int data[] = {1, 3, 12, 5, 13, 8, 0, 2, 7};
exchange_sort(data + 0, data + 8);
for(int *i = data; i <= data + 8; i ++)
{
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}