使用指针法对数组进行冒泡排序、选择排序、插入排序法、二分查找法
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#define N 100
//指针各种排序
//①const 只读
void main2() {
time_t ts;
unsigned int seed = time(&ts);
srand(seed);
int a[N] = {0};
int *pArray[N];
for (int i = 0; i < N; i++)
{
printf("%3d", a[i] = rand() % 100);
*(pArray + i) = a[i];
if ((i+1) % 25 == 0) {
printf("\n");
}
}
printf("\n"); printf("\n");
//*(pArray + i)
//选择排序
//for (int i = 0; i < N; i++)
//{
//for (int j = i+1; j < N; j++)
//{
//if (*(pArray + i) > *(pArray + j))
//{
//int temp = *(pArray + j);
//*(pArray + j) = *(pArray + i);
//*(pArray + i )= temp;
//}
//}
//printf("%3d", pArray[i]);
//if ((i + 1) % 25 == 0) {
//printf("\n");
//}
//}
////冒泡排序
//for (int i = 0; i < N-1; i++)
//{
//for (int j = 0; j < N-1-i; j++)
//{
//if (*(pArray + j)>*(pArray + j+1))
//{
//int temp = *(pArray + j);
//*(pArray + j) = *(pArray + j + 1);
//*(pArray + j + 1) = temp;
//}
//}
//}
//插入排序法
//1、保存一个临时变量
//2、记录那个个临时变量的下标 j
//3、如果这个下标大于0 并且 临时标量 小于 数组[j - 1]这个数字
//①那么就不断往后移动,数组[j] = 数组[j - 1]
//②否则 就是到了该插入的位置了,结束循环,
//③得到最佳位置j 插入数值
for (int i = 1; i < N; i++)
{
int temp = pArray[i];
int j = i;
while (j>0 && temp< pArray[j-1])
{
pArray[j] = pArray[j - 1];
j--;
}
pArray[j] = temp;
}
for (int i = 0; i < N; i++)
{
printf("%3d", pArray[i]);
if ((i + 1) % 25 == 0) {
printf("\n");
}
}
int pNum;
printf("打个数字\n");
scanf("%d", &pNum);
//二分查找法
int high = N - 1;
int low = 0;
int mid = 0;
int flag = 0 ;
while (low <= high) {
mid = (high + low) / 2;
if (pArray[mid] == pNum) {
flag = 1;
break;
}
if (pNum > pArray[mid]) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
printf("\n");
printf(flag?"找到":"没有找到");
system("pause");
}