文章目录
六、short s1 = 1; s1 = s1 + 1;有错吗?short s1 = 1; s1 += 1;有错吗?
对于short s1 = 1; s1 = s1 + 1;由于1是int类型,因此s1+1运算结果也是int 型,需要强制转换类型才能赋值给short型。
而short s1 = 1; s1 += 1;可以正确编译,因为s1+= 1;相当于s1 = (short)(s1 + 1);其中有隐含的强制类型转换。
七、float f=3.4;是否正确?
不正确。精度不准确,应该用强制类型转换,如下所示:float f=(float)3.4 或float f = 3.4f。
在java里面,没小数点的默认是int,有小数点的默认是 double;
八、手动实现一下冒泡排序(快速排序)
1、冒泡排序
代码如下(示例):
public static void main(String[] args) {
int []nums = {1,8,9,6,4,2,7};
int temp;
for (int i = 0; i < nums.length-1; i++) {
for (int j = 0; j < nums.length-i-1; j++) {
if (nums[j] > nums[j+1]) {
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
// 打印数组元素
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");
}
}
输出结果为:
1 2 4 6 7 8 9
2、快速排序
代码如下(示例):
public static void quickSort(int[] arr){
qsort(arr, 0, arr.length-1);
}
private static void qsort(int[] arr, int low, int high){
if (low < high){
int pivot=partition(arr, low, high); //将数组分为两部分
qsort(arr, low, pivot-1); //递归排序左子数组
qsort(arr, pivot+1, high); //递归排序右子数组
}
}
private static int partition(int[] arr, int low, int high){
int pivot = arr[low]; //枢轴记录
while (low<high){
while (low<high && arr[high]>=pivot) --high;
arr[low]=arr[high]; //交换比枢轴小的记录到左端
while (low<high && arr[low]<=pivot) ++low;
arr[high] = arr[low]; //交换比枢轴小的记录到右端
}
//扫描完成,枢轴到位
arr[low] = pivot;
//返回的是枢轴的位置
return low;
}
public static void main(String[] args) {
int []nums = {1,8,9,6,4,2,7};
int temp;
//快速排序
quickSort(nums);
// 打印数组元素
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]+" ");
}
}
输出结果为:
1 2 4 6 7 8 9