排序和查找
import java.util.*;
public class Simple {
public static int randi(int start)
{
return (int) (Math.random() * start);
}
public static int[] randi(int start, int length)
{
int[] rst = new int[length];
for (int i = 0; i < length; i++)
{
rst[i] = randi(start);
}
return rst;
}
public static void p(int[] arr)
{
for (int v: arr)
{
System.out.print(v + " ");
}
System.out.print("\n"); // 'a' char type
// "s" string s
}
public static void bubbleSort(int[] arr)
{
for (int i = arr.length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr, j, j+1);
}
}
p(arr);
}
}
public static int smallestIndex(int[] arr, int start)
{
int min = arr[start];
int minIndex = start;
for (int i = start; i < arr.length; i++)
{
if (arr[i] < min)
{
min = arr[i];
minIndex = i;
}
}
return minIndex;
}
public static int[] bubbleSortNew(int[] arr)
{
int[] rst = new int[arr.length];
for (int i = 0; i < arr.length; i++)
{
rst[i] = arr[i];
}
for (int i = rst.length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (rst[j] > rst[j+1])
{
swap(rst, j, j+1);
}
}
p(rst);
}
return rst;
}
public static void swap(int[] arr, int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void selectSort(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
// int minIndex = smallestIndex(arr, i);
int minIndex = i;
for (int j = i; j < arr.length; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
// swap(arr, i, minIndex);
int tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
public static void selectSort2(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
int minIndex = smallestIndex(arr, i);
swap(arr, i, minIndex);
}
}
public static void insertSort(int[] a)
{
int tmp = 0, j = 0;
for (int i = 0; i < a.length; i++)
{
tmp = a[i];
j = i - 1;
while (j >= 0 && tmp < a[j])
{
a[j+1] = a[j];
j--;
}
a[j+1] = tmp;
}
// p(a);
}
public static int find(int[] arr, int value)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == value)
{
return i;
}
}
return -1;
}
public static int find(ArrayList<String> list, String s)
{
for (int i = 0; i < list.size(); i++)
{
if(list.get(i).equals(s))
{
return i;
}
}
return -1;
}
public static int find(String source, String sub)
{
for (int i = 0; i <= source.length() - sub.length(); i++)
{
if(source.substring(i, i+sub.length()).equals(sub))
{
return i;
}
}
return -1;
}
public static int binarySearch(int[] nums, int v)
{
int low = 0, mid = 0;
int high = nums.length - 1;
while(low <= high)
{
mid = (low + high) / 2;
if(nums[mid] > v)
{
high = mid - 1;
}
else if(nums[mid] < v)
{
low = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
public static void main(String[] args)
{
// System.out.println(find("hello", "l0"));
int[] nums = {75, 39, 39, 73, 51, 60, 65, 84};
bubbleSort(nums);
// p(nums);
System.out.println(binarySearch(nums, 51) + "sadfas");
}
}
不要浅尝辄止要认真深入