#include <unordered_set>
#include <iostream>
#include <algorithm>
using namespace std;
typedef int ElemType;
typedef struct
{
ElemType* data;
int length,MaxSize;
}SqList;
//create
bool InitSq(SqList &L)
{
L.MaxSize = 100;
L.data = (ElemType*)malloc(sizeof(ElemType)*L.MaxSize);
if (L.data == nullptr)
return false;
L.length = 0;
return true;
}
bool destory(SqList &L)
{
if (L.data)
{
free(L.data);
return true;
}
return false;
}
//traversal
void traversal(SqList &L)
{
for (int i = 1; i <= L.length; ++i) {
cout<<L.data[i]<<" ";
}
cout<<endl;
}
//create
void create(SqList &L)
{
int n;
cout<<"please input the lenght of sequence:";
cin>>n;
if(n > L.MaxSize)
L.data = (ElemType*)realloc(L.data,n+L.MaxSize);
L.length = n;
L.MaxSize += n;
cout<<"please input your sequence:";
for (int i = 1; i <= L.length; ++i) {
cin>>L.data[i];
} //L.data[0]不存东西
}
//直接插入排序
void direct_sort(SqList &L)
{
int i,j;
//选择待排序记录
for (i = 2; i <= L.length; ++i) {
if (L.data[i] < L.data[i-1])
{
L.data[0] = L.data[i]; //哨兵
for (j = i-1; L.data[0] < L.data[j] ; --j) {
L.data[j+1] = L.data[j];
}
L.data[++j] = L.data[0];
}
}
}
//折半插入排序
void binary_sort(SqList &L)
{
int i,j,left,right,mid;
//选择待插入记录
for( i = 2 ; i <= L.length ; i++)
{
L.data[0] = L.data[i];
left = 1; right = i - 1;
while (left <= right)
{
mid = (left + right) / 2;
if (L.data[0] < L.data[mid])
right = mid - 1;
else
left = mid + 1;
}
//right+1为待插入位置
//移位
for( j = i-1 ; j >= right+1 ; --j)
L.data[j+1] = L.data[j];
L.data[right+1] = L.data[0];
}
}
//shell 排序
void shell_sort(SqList &L)
{
int dk;
int i,j;
for( dk = L.length/2 ; dk >= 1 ; dk = dk/2 )
{
for( i = dk+1 ; i <= L.length ; ++i)
if (L.data[i] < L.data[i-dk])
{
L.data[0] = L.data[i];
for( j = i-dk ; j >= 0 && L.data[0] < L.data[j] ; j -= dk)
L.data[j+dk] = L.data[j];
L.data[j+dk] = L.data[0];
}
}
}
//顺序查找
int sequnence_search(SqList &L,ElemType x)
{
L.data[0] = x; //哨兵
int i;
for ( i = L.length; L.data[0] != L.data[i]; --i);
return i;
}
//折半查找
int binary_search(SqList &L,ElemType x)
{
int left = 1,right = L.length,mid;
while (left <= right)
{
mid = (left + right)/2;
if (x == L.data[mid])
return mid;
else if (x < L.data[mid])
right = mid - 1;
else
left = mid + 1;
}
return 0; //查找失败
}
int main()
{
SqList L;
if (InitSq(L))
{
create(L);
// direct_sort(L);
binary_sort(L);
// shell_sort(L);
// int i = sequnence_search(L,34);
int i = binary_search(L,32);
if ( i != 0)
cout<<to_string(L.data[i])<<endl;
else
cout<<"don‘t find anything!"<<endl;
traversal(L);
destory(L);
}
return 0;
}
原文:https://www.cnblogs.com/nanfengnan/p/15164592.html