並べ替え------単純な並べ替え
2802 ワード
/*------- ----------
: bubble_sort
:
: ,
:
: O(n^2), O(1);
-- ,
, O(n^2).
-------------------------*/
void bubble_sort(int *bubble, int Length)
{
int i,j;
int temp;
int count;
count = Length;
for(i = 0; i < Length; i++)
{
count--; // , 1;
for(j = 0; j < count; j++)
{
if(bubble[j] < bubble[j+1])
{
temp = bubble[j];
bubble[j] = bubble[j+1];
bubble[j+1] = temp;
}
}
}
}
/*-------- -----------
: insert_sort
:
: ,
:
: O(n^2), O(1);
-------------------------*/
void insert_sort(int *insertion, int Length)
{
int i,j;
int temp;
for(i = 0; i < Length; i++)
{
for(j = i; j >= 1; j--)
{
if(insertion[j] > insertion[j-1])
{
temp = insertion[j];
insertion[j] = insertion[j-1];
insertion[j-1] = temp;
}
}
}
}
/*-------- -----------
: select_sort
:
: ,
:
: O(n^2), O(1);
-------------------------*/
void select_sort(int *selection, int Length)
{
int i, j;
int flag=0,temp;//flag
int Min;
for(i = 0; i < Length; i++)
{
Min = selection[i];
for(j = i; j < Length; j++)
{
if(Min > selection[j])
{
flag = j;
Min = selection[j];
}
}
temp = selection[i];
selection[i] = Min;
selection[flag] = temp;
}
}
泡立ちソートについては、後でlengthパスを行う前にソートしておけば、無駄なループもするので、以下にプログラムを変更してフラグを設定しましたが、交換が発生していない場合は、すでにソートが完了していることを証明します.
void bubble_sort(int *bubble, int Length)
{
int i,j;
int temp;
int count, flag = 0;
count = Length;
for(i = 0; i < Length; i++)
{
count--; // , 1;
for(j = 0; j < count; j++)
{
if(bubble[j] > bubble[j+1])
{
flag = 1;
temp = bubble[j];
bubble[j] = bubble[j+1];
bubble[j+1] = temp;
}
}
if(flag == 0)
{
break;
}
else
{
flag=0;
}
}
}