1.无序数组——顺序查找法,很无语的查找法
2.有序数组——二分查找法
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
/*
* @brief 对数组进行排序
* @param() state:可表示从小到大或从大到小排序
* pArray:指向数组的指针
* length:数组长度
* @return void
*/
void sortData(int *pArray, int length, int state)
{
if (state == 0)
{
}
else if (state == 1)//从小到大排序
{
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - i - 1; j++)
{
if (pArray[j] > pArray[j + 1]) // j >j+1
{
pArray[j] = pArray[j] + pArray[j + 1];
pArray[j+1] = pArray[j] - pArray[j + 1];
pArray[j] = pArray[j] - pArray[j + 1];
}
}
}
}
else if (state == 2)
{
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - i - 1; j++)
{
if (pArray[j] < pArray[j + 1]) // 异或实现数据交换
{
pArray[j] = pArray[j] ^ pArray[j + 1];
pArray[j + 1] = pArray[j] ^ pArray[j + 1];
pArray[j] = pArray[j] ^ pArray[j + 1];
}
}
}
}
}
/*
* @brief 从给定的数组中查找数据
* @param() state:可表示从小到大或从大到小排序
* pArray:指向数组的指针
* length:数组长度
* data:要查找的数据
* @return int*
* 主要是方便插入等操作
*/
int* findData(int *pArray, int length, int state, int data)
{
if (state == 0)
{
for (int i = 0; i < length; i++)
{
printf("第%d次查找\n", i);
if (pArray[i] == data)
{
printf("经过查找%d次,数据查找成功\n", i+1);
return &pArray[i];
}
}
printf("历经千辛万苦,数据查找还是失败\n");
return NULL;
}
//二分查找法
int startIndex, endIndex, middleIndex;
int count = 0;
startIndex = 0;
endIndex = length - 1;
if (state == 1)//从小到大的顺序
{
while (startIndex <= endIndex)
{
printf("第%d次查找\n", ++count);
middleIndex = (startIndex + endIndex) / 2;
printf("中间数据是%d\n", pArray[middleIndex]);
if (pArray[middleIndex] == data)
{
printf("经过查找%d次,数据查找成功\n", count);
return &pArray[middleIndex];
}
else if (pArray[middleIndex] < data)
{
startIndex = middleIndex + 1;
}
else
{
endIndex = middleIndex - 1;
}
}
printf("历经千辛万苦,数据查找还是失败\n");
return NULL;
}
if (state == 2)//从大到小的顺序
{
while (startIndex <= endIndex)
{
printf("第%d次查找\n", ++count);
middleIndex = (startIndex + endIndex) / 2;
printf("中间数据是%d\n", pArray[middleIndex]);
if (pArray[middleIndex] == data)
{
printf("经过查找%d次,数据查找成功\n", count);
return &pArray[middleIndex];
}
else if (pArray[middleIndex] > data)
{
startIndex = middleIndex + 1;
}
else
{
endIndex = middleIndex - 1;
}
}
printf("历经千辛万苦,数据查找还是失败\n");
return NULL;
}
}
int main()
{
int num;
int a[20] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
printf("请输入要查找的数据:");
scanf("%d", &num);
int *p = a;
findData(p,20,0,num);
printf("对数组数据按照从小到大顺序排序\n");
sortData(p, 20, 1);
findData(p, 20, 1, num);
printf("对数组数据按照从大到小顺序排序\n");
sortData(p, 20, 2);
findData(p, 20, 2, num);
system("pause");
return 0;
}