快速排序 求旋轉陣列最小數字

2021-07-12 01:39:12 字數 2559 閱讀 7755

#include #include #include #include using namespace std;

// 快速排序1

void quicksort( int a, int l, int r )

int i = l;

int j = r;

int mid = ( l + r ) / 2;

int tmp = a[mid];

a[mid] = a[l];

a[l] = tmp;

int value = a[l];

while( i < j )

a[i] = value;

quicksort( a, l, i - 1 );

quicksort( a, i + 1, r );

return;

}// 快速排序2,容易理解的快排

void quicksort1( int a, int start, int end )

int mid = ( start + end ) / 2;

int tmp = a[mid];

a[mid] = a[end];

a[end] = tmp;

int idx = start - 1;

for( int i = start; i < end; i++ )

} } idx++;

tmp = a[idx];

a[idx] = a[end];

a[end] = tmp;

quicksort1( a, start, idx - 1 );

quicksort1( a, idx + 1, end );

return;

}void print( int a, int len )

cout << endl;

return;

}// 求旋轉陣列的最小數字 遞迴實現

int midrotatedarray( int a, int start, int end )

if( start >= end )

int mid = ( start + end ) / 2;

//if( a[mid] <= a[ ( mid + 1 ) %

int right = mid + 1 > end ? start : mid + 1;

int left = mid - 1 < start ? end: mid - 1;

if( a[mid] <= a[right] && a[mid] <= a[left] )

}int minleft = midrotatedarray( a, start, mid - 1 );

int minright = midrotatedarray( a, mid + 1, end );

return minleft > minright ? minright : minleft; }

// 求旋轉陣列的最小數字 非遞迴實現

int midrotatedarray_norecur( int a, int start, int end )

if( start >= end )

int mid = ( start + end ) / 2;

while( a[start] >= a[end] )

} if( a[start] == a[mid] && a[mid] == a[end] ) // 順序查詢, for : and

}return min;

} if( start != mid && a[start] >= a[mid] )

else

}min = a[start];

return min;

}// 總結: 先寫測試用例,否則很多考慮不周

int main()

; int b1 = ;

int b2 = ;

int b3 = ;

int b4 = ;

int b5 = ;

int b6 = ;

int b7 = ;

int *b8 = null;

cout << midrotatedarray( b7, 0, 0 ) << endl;

cout << midrotatedarray_norecur( b7, 0, 0 ) << endl;

int a1 = ;

int a2 = ;

int a3 = ;

int a4 = ;

int a5 = ;

quicksort1( a1, 0, 4 );

quicksort1( a2, 0, 4 );

quicksort1( a3, 0, 4 );

quicksort1( a4, 0, 4 );

quicksort1( a5, 0, 4 );

print( a1, 5 );

print( a2, 5 );

print( a3, 5 );

print( a4, 5 );

print( a5, 5 );

return ret;

}

求旋轉陣列的最小數字

package com.study 求旋轉陣列的最小數字 設定 輸入遞增排序陣列的乙個旋轉 要求返回最小的數 public class suanfa6 private static int arr private static int arr private static int arr priva...

旋轉陣列最小數字

把乙個陣列最開始的若干個元素搬到陣列的末尾,我們稱之為陣列的旋轉。輸入乙個遞增排序的陣列的乙個旋轉,輸出旋轉陣列的最小元素。例如陣列 為的乙個旋轉,該陣列的最小值為1。code int min int numbers,int length int low 0 int high length 1 in...

旋轉陣列最小數字

旋轉陣列最小數字 劍指offer 二分查詢 題目描述 把乙個陣列最開始的若干個元素搬到陣列的末尾,我們稱之為陣列的旋轉。輸入乙個遞增排序的陣列的乙個旋轉,輸出旋轉陣列的最小元素。解題思路 題目要求找到最小元素,第一反應是排序,但陣列基本有序直接排序浪費效能。結合資料的特點前半部分遞增,後半部分遞減,...