学习内容
排序算法
冒泡排序
选择排序
插入排序
具体内容
冒泡排序
做题思路
1、首先要对数组的元素进行两两之间的比较,之后进行交换,使得最大的元素在最后一个位置
2、不断循环上述步骤
解题
class Solution {
public int[] sortArray(int[] nums) {
return bubblesort(nums,nums.length);
}
//得到最后一个位置为最大值的方法
public void bubble(int[] nums,int n){
//之所以是n-1,是因为我们不断与后一值进行比较,若是为n会超出范围
for(int i = 0 ;i < n-1;i++){
int temp = 0;
if(nums[i] > nums[i+1]){
temp = nums[i];
nums[i] = nums[i+1];
nums[i+1] = temp;
}
}
}
//不断循环上述方法
public int[] bubblesort(int[] nums,int n){
while(n >= 1){
bubble(nums,n);
n--;
}
return nums;
}
}
选择排序
做题思路
1、假设第一个元素最大值,再从数组里选出一个最大值,与最后一个元素进行交换,从而使最大元素在最后一个位置
解题
class Solution {
public int[] sortArray(int[] nums) {
selectionsort(nums,nums.length);
return nums;
}
//该方法用于找出数组最大元素的位置
public int selection(int[] nums,int n){
//假设第一个元素是最大值
int temp = 0;
int num = nums[0];
for(int i = 0; i < n;i++){
if(num > nums[i]){
num = nums[i];
temp = i;
}
}
return temp;
}
//交换位置切不断循环
public void selectionsort(int[] nums,int n){
while(n > 1){
int temp1 = selection(nums,n);
//进行交换
int temp2 = nums[temp1];
nums[temp1] = nums[n-1];
nums[n-1] = temp2;
n--;
}
}
}
插入排序
做题思路
1、将第一个元素作为最小元素,之后后面的数字从后向前进行比较,若是比前面小,就不断往前,比前面大,就插入当前位置
解题
class Solution {
public int[] sortArray(int[] nums) {
selectionsort(nums,nums.length);
return nums;
}
//插入方法,n表示当前该元素的位置
public void insert(int[] nums,int n){
int temp = nums[n];
int i = n;
while(nums[i-1] > temp){
nums[i] = nums[i-1];
i--;
//若是该值为最小值
if(i == 0){
break;
}
}
nums[i] = temp;
}
//不断循环该方法
public void insertsort(int[] nums,int n){
for(int i = 1;i <= n-1;i++){
insert(nums,i);
}
}
}
总结
冒泡比较的是两个元素的大小(一交换,二循环),选择是提取当前数组对象的最大值放最后面(一找最大值,二循环交换),插入是当前元素从后往前比较(一比较,二循环)