sort
#include<stdio.h>
int a[10010];
void quick_sort(int a[], int l, int r) {
if (l >= r) {
return;
}
int i = l - 1, j = r + 1, x = a[l + r >> 1];
while (i < j) {
do {
i += 1;
} while (a[i] < x);
do {
j -= 1;
} while (a[j] > x);
if (i < j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
quick_sort(a, l, j);
quick_sort(a, j + 1, r);
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
quick_sort(a, 0, n - 1);
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
return 0;
}
binary search
#include<stdio.h>
int a[10010];
void quick_sort(int a[], int l, int r) {
if (l >= r) {
return;
}
int i = l - 1, j = r + 1, x = a[l + r >> 1];
while (i < j) {
do {
i += 1;
} while (a[i] < x);
do {
j -= 1;
} while (a[j] > x);
if (i < j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
quick_sort(a, l, j);
quick_sort(a, j + 1, r);
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
quick_sort(a, 0, n - 1);
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
int x;
scanf("%d", &x);
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r >> 1;
if (a[mid] >= x) {
r = mid;
}
else {
l = mid + 1;
}
}
if (a[l] != x) {
printf("该数字不存在");
} else {
printf("该数字的位置为:%d", l + 1);
}
return 0;
}
暴力
#include<stdio.h>
int a[10010];
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int x;
scanf("%d", &x);
for (int i = 0; i < n; i++) {
if (a[i] == x) {
printf("idx is %d", i + 1);
return 0;
}
}
printf("this number is null");
return 0;
}