现场面试常见的手写代码基础题
冒泡排序(O(n2))(升序)
void BubbleSort(int *inputData, int length)
{
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length-i-1; j++)
{
if (inputData[j] > inputData[j+1])
{
int tmp = inputData[j];
inputData[j] = inputData[j+1];
inputData[j+1] = tmp;
}
}
}
}
int main()
{
int n;
cin >> n ;
int b[100];
for (int i = 0; i> b[i];
BubbleSort(b, n);
for (int j = 0; j < n; j++)
{
cout << b[j] << endl;;
}
return 0;
}
二分查找+快排
int BinarySearch(int arr[], int length,int val)
{
if (arr == NULL || length < 1)
return -1;
else
{
int right = length - 1;
int left = 0;
int mid = 0;
while (left <=right)
{
mid = (right + left) >> 1;
if (arr[mid] == val)
return mid;
else if (arr[mid] > val)
{
right = mid - 1;
}
else if (arr[mid] < val)
{
left = mid + 1;
}
}
return -1;
}
}
int Partition(int arr[], int low, int high)
{
if (arr == NULL )
return -1;
int mid = arr[low];
while (low < high)
{
while(low=mid))
{
high--;
}
arr[low] = arr[high];
while (low < high && (arr[low] < mid))
{
low++;
}
arr[high] = arr[low];
}
arr[low] = mid;
return low;
}
void QSort(int arr[],int low, int high)
{
while(low < high)
{
int pivot = Partition(arr, low, high);
QSort(arr, low, pivot - 1);
QSort(arr, pivot + 1, high);
}
}
int main()
{
int n,val;
cin >> n>>val ;
int key;
int b[100];
for (int i = 0; i < n; i++)
{
cin >> b[i];
}
QSort(b, 0,n-1);
key = BinarySearch(b, n, val);
cout << key << endl;
return 0;
}