Java设计顺序表的顺序查找算法,将哨兵设在下标高端。
package com.programmercarl.linkedlist.homework;
/**
* @ClassName Select
* @Descriotion TODO
* @Author nitaotao
* @Date 2022/5/5 17:15
* @Version 1.0
**/
public class Select {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 9, 9, 10};
getIndex(arr, 0);
getIndex(arr, 1);
getIndex(arr, 9);
getIndex(arr, 10);
getIndex(arr, 11);
}
public static void getIndex(int[] arr, int target) {
//设置哨兵
int end = arr.length;
if (arr[end - 1] < target || arr[0] > target) {
System.out.println("查找到元素 " + target + " 不在当前顺序表中");
}
for (int i = 0; i < end; i++) {
if (arr[i] == target) {
System.out.println("查找到元素 " + target + " 位置为:" + i);
}
}
}
}
C
//
// Created by nitaotao on 2022/5/8.
//
#include
void getIndex(int arr[], int target, int size) {
//设置哨兵
int end = size;
if (arr[end - 1] < target || arr[0] > target) {
printf("%s%d%s\n", "查找到元素 ", target, " 不在当前顺序表中");
return;
}
for (int i = 0; i < end; i++) {
if (arr[i] == target) {
printf("%s%d%s%d\n", "查找到元素 ", target, " 位置为:", i);
}
}
}
int main() {
int arr[] = {1, 3, 5, 9, 9, 10};
int size = sizeof(arr) / sizeof(arr[0]);
//方法里传过去的只是首地址
getIndex(arr, 0, size);
getIndex(arr, 1, size);
getIndex(arr, 9, size);
getIndex(arr, 10, size);
getIndex(arr, 11, size);
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)