33,007
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class Link {
public:
double dData;
Link* pNext;
Link(double dd) : dData(dd), pNext(NULL) {}
void displayLink() {
cout << dData << " ";
}
};
class SortedList {
private:
Link* pFirst;
public:
SortedList() : pFirst(NULL) {}
~SortedList() {
Link* pCurrent = pFirst;
while(pCurrent != NULL) {
Link* pOldCur = pCurrent;
pCurrent = pCurrent->pNext;
delete pOldCur;
}
}
bool isEmpty() {
return (pFirst == NULL);
}
void insert(double key) {
Link* pNewLink = new Link(key);
Link* pPrevious = NULL;
Link* pCurrent = pFirst;
while(pCurrent != NULL && key > pCurrent->dData) {
pPrevious = pCurrent;
pCurrent = pCurrent->pNext;
}
if(pPrevious == NULL)
pFirst = pNewLink;
else
pPrevious->pNext = pNewLink;
pNewLink->pNext = pCurrent;
}
void remove() {
Link* pTemp = pFirst;
pFirst = pFirst->pNext;
delete pTemp;
}
void displayList() {
cout << "List (first-->last): ";
Link* pCurrent = pFirst;
while(pCurrent != NULL) {
pCurrent->displayLink();
pCurrent = pCurrent->pNext;
}
cout << endl;
}
};
int main() {
SortedList theSortedList;
theSortedList.insert(20);
theSortedList.insert(40);
theSortedList.displayList();
theSortedList.insert(10);
theSortedList.insert(30);
theSortedList.insert(50);
theSortedList.displayList();
theSortedList.remove();
theSortedList.displayList();
return 0;
}
//希尔排序
void shellsort(int * array,int k)
{
int m=k;
while (m>1)
{
m=(m+1)/2;
for (int i=m;i<k;i++)
{
int temp=array[i];
int j=i;
while (j>=m&&temp<array[j-m])
{
array[j]=array[j-m];
j-=m;
}
array[j]=temp;
}
}
}
自己写错了的希尔,因为冒泡不一定就能对,但是排完之后已经基本有序了,所以最后用冒泡啊,用插入啊,都很快的!
void sort(int *array,int n)
{
int m=n,temp;
while ( m>1 )
{
m=(m+1)/2;
for ( int i=0; i+m<n; i++)
{
if ( array[i]>array[i+m] )
{
temp=array[i];
array[i]=array[i+m];
array[i+m]=temp;
}
}
}
bool b=1;
int i,j;
for (i=1;i<n&&b==1;++i)
{
b=0;
for (j=0;j<n-i;++j)
{
if (array[j]>array[j+1])
{
b=1;
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
}