本文的目的是了解C语言下的选择排序,并分别在C与MFC下实现选择排序。
下面是在MFC下的程序实现:
char tmp[10] = "";
int rand_num[10];
CString str[10];
CString result;
CString sort_result;
void CNM_MFCDlg::OnBnClickedOk()
{
CEdit* pBoxOne;
pBoxOne = (CEdit*) GetDlgItem(IDC_EDIT1);
srand((unsigned)time(NULL));
for(int x=0; x<10; x++)
{
rand_num[x] = rand()%100;
str[x] = itoa(rand_num[x],tmp,10);
result = result + str[x] + _T(" ");
}
pBoxOne-> SetWindowText( result );
//MessageBox(str,_T("程序运行结果"),MB_OK);
result.ReleaseBuffer();
}
void CNM_MFCDlg::OnBnClickedButton1()
{
CEdit* pBoxTwo;
pBoxTwo = (CEdit*) GetDlgItem(IDC_EDIT2);
selection_sort(rand_num,10);
for(int x=0; x<10; x++)
{
str[x] = itoa(rand_num[x],tmp,10);
sort_result = sort_result + str[x] + _T(" ");
}
sort_result = sort_result + _T("~ \r\n");
//UpdateData(false);
pBoxTwo-> SetWindowText( sort_result );
sort_result.ReleaseBuffer();
}
void CNM_MFCDlg::OnBnClickedCancel()
{
CDialogEx::OnCancel();
}
void selection_sort(int *a,int n)
{
int i,j,s;
for(i=0;i
{
s=i;
for(j=i+1;j
{
if(a[j]
{
s=j;
}
}
swap(&a[i],&a[s]);
}
}
/*
实现两个元素的互换
原型:void swap(int *p1,int *p2)
参数:int *p1:元素1的地址
int *p2:元素2的地址
*/
void swap(int *p1,int *p2)
{
int temp;
temp=*p1;
*p1=*p2;
*p2=temp;
}
程序运行结果如下:
关于选择排序算法,其函数这样:
/*
使用选择排序法进行排序:从小到大;
void selection_sort(int *a,int n)
参数:int *a:数组名
int n :排序元素数
*/
void selection_sort(int *a,int n)
{
int i,j,s;
for(i=0;i
{
s=i;
for(j=i+1;j
{
if(a[j]