Java数据结构与算法代码
时间: 2023-10-01 09:02:29 浏览: 136
下面展示了一些Java数据结构与算法的代码实现:
冒泡排序代码实现O(n^2):
```java
public class Bubble {
/* 对数组a中的元素进行排序 */
public static void sort(Comparable[] a){
for(int i=a.length-1;i>0;i--){
for(int j=0;j<i;j++){
// 比较索引j和索引j+1处的值
if (greater(a[j],a[j+1])){
exch(a,j,j+1);
}
}
}
}
/* 比较v元素是否大于w元素 */
private static boolean greater(Comparable v,Comparable w){
return v.compareTo(w)>0;
}
/* 数组元素i和j交换位置 */
private static void exch(Comparable[] a,int i,int j){
Comparable temp;
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
```
归并排序代码实现测试:
```java
public class MergeTest {
public static void main(String[] args) {
Integer[] array = {4, 6, 8, 7, 9, 2, 10, 1,12};
MergeSort.sort(array);
System.out.println(Arrays.toString(array));
}
}
```
快速排序代码实现测试:
```java
public class QuickTest {
public static void main(String[] args) {
Integer[] array = {4, 6, 8, 7, 9, 2, 10, 1,12,10};
QuickSort.sort(array);
System.out.println(Arrays.toString(array));
}
}
```<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [二、Java数据结构与算法---排序(讲解与代码)](https://blog.csdn.net/Royalic/article/details/119427212)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文