JAVA排序方法介绍

    科技2025-06-17  38

    1、选择排序selectionSort

    selectionSort:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置。再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。重复第二步,直到所有元素均排序完毕,图示所下,JAVA代码,完成对数组A进行排序并输出。

    int A[] = {9,1,2,5,7,4,8,6,3,5}; System.out.print("选择排序前为:"); for (int x = 0; x < A.length; x++) System.out.print(A[x]+" "); System.out.println(); for (int i = 0; i < A.length; i++) { int minIndex = i; for (int x = i + 1; x < A.length; x++) { if (A[x] < A[minIndex]) { int temp = A[x]; A[x] = A[minIndex]; A[minIndex] = temp; } } } System.out.print("选择排序后为:"); for (int x = 0; x < A.length; x++) System.out.print(A[x]+" "); System.out.println();

    2、冒泡排序bubbleSort

    bubbleSort: 把相邻的元素两两进行比较,根据大小交换元素的位置,图示所下,JAVA代码,完成对数组A进行排序并输出。

    int A[] = {9,3,1,4,2,7,8,6,5}; System.out.print("冒泡排序前为:"); for (int z = 0; z < A.length; z++) System.out.print( A[z] + " "); System.out.println(); for (int y = 0; y < A.length; y++) { for (int z = 0; z < A.length - 1; z++) { if (A[y] < A[z]) { int replace = A[z]; A[z] = A[y]; A[y] = replace; } } } System.out.print("冒泡排序后为:"); for (int z = 0; z < A.length; z++) System.out.print( A[z] + " "); System.out.println();

    3、折半查找binarySearch

    binarySearch:是一种算法,其输入是一个有序的元素列表(必须是有序的),如果查找的元素包含在列表中,二分查找返回其位置,否则返回NULL。图示 JAVA代码,完成对数组A[5,9,1,6,8],找出数字8,如果存在输出所在位置,不存在输出“不存在”。

    int A[] = { 5,9,1,6,8}; for (int y = 0; y < A.length; y++) //1.先排序 { for (int z = 0; z < A.length - 1; z++) { if (A[y] < A[z]) { int replace = A[z]; A[z] = A[y]; A[y] = replace; } } } System.out.print("排序后为:"); for (int z = 0; z < A.length; z++) System.out.print( A[z] + " "); System.out.println(); int left = 0; //2.后查找 int right = A.length - 1; int search = 1; //要查找的元素为8 boolean target = false; while (left <= right) { int mid = (left + right) / 2; if (A[mid] > search) { right = mid - 1; } else if (A[mid] < search) { left = mid + 1; } else { System.out.println("该位置在第"+(mid+1)+"位置"); target = true; break; } } if(!target) System.out.println("找不到该元素");

    4、字符串匹配stringMatch

    stringMatch: 长度为m的字符串source中,寻找长度为n的字符串target。如果source字符串中存在target字符串,则返回字符串target第一次在字符串source中出现的位置;如果不存在,则返回-1,图示 JAVA代码,完成对字符串A“ymytkf”,找出字符串B“my”的在字符串的位置,存在输出位置。

    以下为C++代码 (JAVA等待更新)

    string A = "ymytkf"; //原 string B = "my"; //目标 bool target = false; int lenA = A.size(); int lenB = B.size(); int x; for (int i = 0; i <= lenA; i++) { for (x = 0; x < lenB; x++) { if (A[i + x] != B[x]) { break; } } if (x == lenB) { cout << "该元素在第" << i + 1 << "位上" << endl; target = true; break; } } if(!target) cout << "不存在" << endl;
    Processed: 0.015, SQL: 8