题目来自网络
题目(1):基于数组的插入排序
思路:总是把待排序元素插入已排序的元素集合中,程序的重点是查找待排序元素的位置。
查找待排序元素的位置时,
对于数组,既可以从前往后找,也可以由后往前找。
对于链表,可以从前往后找。
代码:
void InsertSort(int nArr[],int nLen)
{
int j = 0;
for (int i = 2;i <= nLen;i++)
{
if (nArr[i] < nArr[i - 1])
{
nArr[0] = nArr[i];
j = i - 1;
while(nArr[0] < nArr[j])
{
nArr[j + 1] = nArr[j];
j--;
}
nArr[j + 1] = nArr[0];
}
}
}
题目(2):基于链表的插入排序
思路:基于链表的插排,可以看成一个旧链表中的一个结点要插入到一个新链表的结点中。
代码:
#include <iostream>
using namespace std;
struct ListNode
{
int m_nData;
ListNode* pNext;
};
void InsertSort(ListNode*& pHead)
{
ListNode* pCurOld = pHead;
ListNode* pCurOldNext = pHead;
ListNode* pCurNew = pHead;
ListNode* pLast = NULL;
pHead = NULL;
while(pCurOld != NULL)
{
pCurOldNext = pCurOld -> pNext;
if (pHead == NULL)
{
pCurOld->pNext = pHead;
pHead = pCurOld;
pLast = pCurOld;
}
else if (pHead->m_nData > pCurOld->m_nData)
{
pCurOld->pNext = pHead;
pHead = pCurOld;
}
else if (pLast->m_nData <= pCurOld->m_nData)
{
pLast->pNext = pCurOld;
pCurOld->pNext = NULL;
pLast = pCurOld;
}
else
{
pCurNew = pHead;
while(pCurNew->pNext->m_nData < pCurOld->m_nData)
{
pCurNew = pCurNew->pNext;
}
pCurOld->pNext = pCurNew->pNext;
pCurNew->pNext = pCurOld;
}
pCurOld = pCurOldNext;
}
}
void Print(ListNode* pHead)
{
while(pHead != NULL)
{
cout<<pHead->m_nData<<" ";
pHead = pHead->pNext;
}
cout<<endl;
}
void CreateList(ListNode** pHead,int nLen)//头指针使用指针的指针
{
ListNode* pCur = NULL;
ListNode* pNewNode = NULL;
for (int i = 0;i < nLen;i++)
{
pNewNode = new ListNode;
cin>>pNewNode->m_nData;
pNewNode->pNext = NULL;
if (*pHead == NULL)
{
*pHead = pNewNode;
pCur = *pHead;
}
else
{
pCur->pNext = pNewNode;
pCur = pNewNode;
}
}
}
int main()
{
int nLen = 4;
ListNode* pHead = NULL;
CreateList(&pHead,nLen);
InsertSort(pHead);
Print(pHead);
system("pause");
return 1;
}