面试题14调整数组顺序使奇数在偶数之前

https://blog.csdn.net/u010425776/article/details/50877321

本题详细解析都已在代码中注释了:

  1. /**
  2. * 题目:输入一个数组,要求将奇数放在数组的前半段,偶数放在数组的后半段
  3. * @author 大闲人柴毛毛
  4. */
  5. public class Reorder {
  6. /**
  7. * 分析:本题只要求前半段为奇数,后半段为偶数,没有要求有序,
  8. * 因此可以采用快速排序中一趟排序的思想:
  9. * 使用两个指针i、j,i指向头、j指向尾,分别向后、向前扫描;
  10. * 若i遇到偶数则停下,j遇到奇数则停下,交换这两个数,
  11. * 然后继续重复上述操作,直到i、j相遇为止。代码如下:
  12. * PS:快速排序算法请看我的博客《剑指 offer——快速排序》
  13. */
  14. public static boolean reorder(int[] a){
  15. //若数组为空
  16. if(a== null || a.length== 0){
  17. System.out.println( "数组为空!");
  18. return false;
  19. }
  20. //若数组只有一个元素,那不做任何操作
  21. if(a.length== 1){
  22. System.out.println( "数组长度为1,无需排序!");
  23. return true;
  24. }
  25. //若数组长度超过2,则进行排序
  26. int i= 0,j=a.length- 1;
  27. while(i<j){
  28. //i从头向后扫描,若当前元素为奇数,则继续往后扫描,若为偶数,i停止扫描。
  29. while(a[i]% 2== 1)
  30. i++;
  31. //j从后向前扫描,若当前元素为偶数,则继续往前扫描,若为奇数,j停止扫描。
  32. while(a[j]% 2== 0)
  33. j--;
  34. //当i、j都停止时,如果i和j还没有相遇,就交换这两个数
  35. if(i<j){
  36. int temp = a[i];
  37. a[i] = a[j];
  38. a[j] = temp;
  39. }
  40. }
  41. return true;
  42. }
  43. /**
  44. * 上述代码运行过后会出现死循环!
  45. * 当数组全为奇数时,i无限向后寻找,因此出现死循环。
  46. * 因此,在i向后、j向前的循环中应多加一个判断:若i搜索到末尾,则停止、若j搜索到开头,则停止。
  47. * 修改后的代码如下:
  48. */
  49. public static boolean reorder_modify(int[] a){
  50. //若数组为空
  51. if(a== null || a.length== 0){
  52. System.out.println( "数组为空!");
  53. return false;
  54. }
  55. //若数组只有一个元素,那不做任何操作
  56. if(a.length== 1){
  57. System.out.println( "数组长度为1,无需排序!");
  58. return true;
  59. }
  60. //若数组长度超过2,则进行排序
  61. int i= 0,j=a.length- 1;
  62. while(i<j){
  63. //i从头向后扫描,若当前元素为奇数,则继续往后扫描,若为偶数,i停止扫描。
  64. while(i<a.length- 1 && a[i]% 2== 1)
  65. i++;
  66. //j从后向前扫描,若当前元素为偶数,则继续往前扫描,若为奇数,j停止扫描。
  67. while(j> 0 && a[j]% 2== 0)
  68. j--;
  69. //当i、j都停止时,如果i和j还没有相遇,就交换这两个数
  70. if(i<j){
  71. int temp = a[i];
  72. a[i] = a[j];
  73. a[j] = temp;
  74. }
  75. }
  76. return true;
  77. }
  78. }


猜你喜欢

转载自blog.csdn.net/qq_20398345/article/details/80879027