随笔分类 -  Search & Sort

摘要:set请写出堆排序的代码。输入n个整数,找出其中最小的k个数。1、思路: 堆排序分为建堆(insertion)和取根数据(delete root)。每一步都涉及到堆调整,堆调整算法的时间复杂度为O(logn)。HeapSort 1 #include <stdio.h> 2 3 #define heap_parent(npos) ((int)(((npos) - 1) / 2)) 4 #define heap_left(npos) ((npos) * 2 + 1) 5 #define heap_right(npos) ((npos) * 2 + 2) 6 7 void Swap(in 阅读全文

posted @ 2013-04-07 13:53 月moon鸟 阅读(239) 评论(0) 推荐(0)

摘要:请在较短的时间内写出归并排序的程序。在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组, 求出该数组中的逆序对的总数。1、思路: 二叉树后序遍历的思想,即先递归排序左右子树,然后才是根节点。时间复杂度O(nlogn),空间复杂度O(n)。MergeSort 1 #include <stdio.h> 2 #include <assert.h> 3 4 void PrintArray(int* data, int length) 5 { 6 for (int i = 0; i < length; i++) 7 printf(&q 阅读全文

posted @ 2013-03-30 19:55 月moon鸟 阅读(252) 评论(0) 推荐(0)

摘要:在字符串中找出第一个只出现一次的字符。(35)对公司员工的年龄进行统计排序。计数排序(适用于有边界的数值统计)。1、思路: 因为字符只有256个数字,设置一个hashtable只有256*4=1K字节,这样时间复杂度只有O(n)。 FirstNotRepeatingChar 1 char FirstNotRepeatingChar(char* pString) 2 { 3 if(pString == NULL) 4 return '\0'; 5 6 const int tableSize = 256; 7 unsigned int hashTable... 阅读全文

posted @ 2013-03-27 14:41 月moon鸟 阅读(189) 评论(0) 推荐(0)

摘要:快排的递归版本和非递归版本。数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。(29)输入n个数,找出其中最小的k个数。(30)1、思路: 递归版本:首先随机选定分割数,对数组中小于该分割数的放在左侧,大于该分割数的放在右侧。递归处理左侧和右侧的数字。QuickSort 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <exception> 4 5 void PrintArray(int* data, int length) 6 { 7 for (int i = 0; i < le 阅读全文

posted @ 2013-03-27 14:32 月moon鸟 阅读(299) 评论(0) 推荐(0)

摘要:请快速写出二分查找的代码。把一个数组最开始的若干个元素搬到数组的末尾,叫数组的旋转。输入一个递增排序的数组的一个旋转,输出数组的最小元素。(8)统计一个数字在排序数组中出现的次数。(38)1、思路: 要求输入数组是排序的,这样二分查找的算法是log(n)。BinarySearch 1 int BinarySearch(int data[], int length, int key) 2 { 3 int low, high, mid; 4 low = 0; 5 high = length - 1; 6 while (low <= high) 7 { 8 ... 阅读全文

posted @ 2013-03-27 14:29 月moon鸟 阅读(195) 评论(0) 推荐(0)

导航