常见的软件算法有哪几种?
常见的软件算法包括但不限于以下几种:
常见的排序算法有哪几种,请用Java代码举出各个例子
常见的排序算法包括但不限于以下几种:
下面是使用Java代码实现这些算法的示例:
public static void bubbleSort(int[] arr){
for(int i=0; i<arr.length-1; i++){
for(int j=0; j<arr.length-i-1; j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public static void quickSort(int[] arr, int left, int right){
if(left < right){
int pivot = partition(arr, left, right);
quickSort(arr, left, pivot-1);
quickSort(arr, pivot+1, right);
}
}
public static int partition(int[] arr, int left, int right){
int pivot = arr[left];
while(left < right){
while(left < right && arr[right] >= pivot){
right--;
}
arr[left] = arr[right];
while(left < right && arr[left] <= pivot){
left++;
}
arr[right] = arr[left];
}
arr[left] = pivot;
return left;
}
public static void insertionSort(int[] arr){
for(int i=1; i<arr.length; i++){
int j = i-1;
int temp = arr[i];
while(j >= 0 && arr[j] > temp){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = temp;
}
}
public static void selectionSort(int[] arr){
for(int i=0; i<arr.length-1; i++){
int minIndex = i;
for(int j=i+1; j<arr.length; j++){
if(arr[j] < arr[minIndex]){
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
public static void mergeSort(int[] arr, int left, int right){
if(left < right){
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid+1, right);
merge(arr, left, mid, right);
}
}
public static void merge(int[] arr, int left, int mid, int right){
int[] temp = new int[right-left+1];
int i = left;
int j = mid+1;
int k = 0;
while(i <= mid && j <= right){
if(arr[i] <= arr[j]){
temp[k++] = arr[i++];
}else{
temp[k++] = arr[j++];
}
}
while(i <= mid){
temp[k++] = arr[i++];
}
while(j <= right){
temp[k++] = arr[j++];
}
for(int l=0; l<temp.length; l++){
arr[left+l] = temp[l];
}
}
public static void heapSort(int[] arr){
for(int i=arr.length/2-1; i>=0; i--){
adjustHeap(arr, i, arr.length);
}
for(int j=arr.length-1; j>0; j--){
int temp = arr[0];
arr[0] = arr[j];
arr[j] = temp;
adjustHeap(arr, 0, j);
}
}
public static void adjustHeap(int[] arr, int i, int length){
int temp = arr[i];
for(int k=i*2+1; k<length; k=k*2+1){
if(k+1 < length && arr[k] < arr[k+1]){
k++;
}
if(arr[k] > temp){
arr[i] = arr[k];
i = k;
}else{
break;
}
}
arr[i] = temp;
}