用mfc实现二分法排序
时间: 2023-12-10 17:48:39 浏览: 32
二分法排序,也称二分查找法,是一种基于比较的排序算法。其基本思想是将待排序的序列分为两个子序列,然后对这两个子序列分别进行排序,最终将它们合并成一个有序序列。
以下是用MFC实现二分法排序的示例代码:
```cpp
void CBinarySortDlg::OnBtnSort()
{
CString strInput;
m_editInput.GetWindowText(strInput);
int nCount = strInput.GetLength();
if (nCount <= 0)
{
MessageBox(_T("请输入待排序的数字序列"), _T("提示"), MB_OK | MB_ICONWARNING);
return;
}
int* pData = new int[nCount];
for (int i = 0; i < nCount; i++)
{
pData[i] = _ttoi(strInput.Mid(i, 1));
}
BinarySort(pData, nCount);
CString strOutput;
for (int i = 0; i < nCount; i++)
{
strOutput.AppendFormat(_T("%d"), pData[i]);
}
m_editOutput.SetWindowText(strOutput);
delete[] pData;
}
void CBinarySortDlg::BinarySort(int* pData, int nCount)
{
if (nCount <= 1)
return;
int nMid = nCount / 2;
BinarySort(pData, nMid);
BinarySort(pData + nMid, nCount - nMid);
int* pTemp = new int[nCount];
int i = 0, j = nMid, k = 0;
while (i < nMid && j < nCount)
{
if (pData[i] <= pData[j])
pTemp[k++] = pData[i++];
else
pTemp[k++] = pData[j++];
}
while (i < nMid)
pTemp[k++] = pData[i++];
while (j < nCount)
pTemp[k++] = pData[j++];
for (i = 0; i < nCount; i++)
pData[i] = pTemp[i];
delete[] pTemp;
}
```
在这个示例代码中,首先获取用户在输入框中输入的数字序列,并将其存储在一个动态数组中。然后调用BinarySort函数对整个序列进行排序。在BinarySort函数中,如果当前序列的元素数量小于等于1,则直接返回;否则将当前序列分为两个子序列,对这两个子序列分别进行排序,最后将它们合并成一个有序序列。在合并的过程中,使用一个临时数组来存储排序后的结果,并将结果复制回原数组中。最后将排序后的数字序列显示到输出框中。