6-10 二分查找
注意notfound的用法
Position BinarySearch( List L, ElementType x ) { int left = 1; int right = L->Last; while(left <= right) { int mid = (left + right )/2; if(L->Data[mid] == x) return mid; else if(L->Data[mid] > x) { right = mid-1; } else { left = mid + 1; } } return NotFound; }
7-12 排序
#include<stdio.h> #include<stdlib.h> int cmp(const void* a,const void* b) { return (*(int*)a-*(int*)b); } int a[100004]; int main() { int x; scanf("%d",&x); for(int i=0;i<x;i++) { scanf("%d",&a[i]); } qsort(a,x,sizeof(int),cmp); for(int j=0;j<x;j++) { if(j!=0) printf(" "); printf("%d",a[j]); } }
6-2 顺序表操作集
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 5 #define ERROR -1 typedef enum {false, true} bool; typedef int ElementType; typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存线性表中最后一个元素的位置 */ }; List MakeEmpty(); Position Find( List L, ElementType X ); bool Insert( List L, ElementType X, Position P ); bool Delete( List L, Position P ); int main() { List L; ElementType X; Position P; int N; L = MakeEmpty(); scanf("%d", &N); while ( N-- ) { scanf("%d", &X); if ( Insert(L, X, 0)==false ) printf(" Insertion Error: %d is not in.\n", X); } scanf("%d", &N); while ( N-- ) { scanf("%d", &X); P = Find(L, X); if ( P == ERROR ) printf("Finding Error: %d is not in.\n", X); else printf("%d is at position %d.\n", X, P); } scanf("%d", &N); while ( N-- ) { scanf("%d", &P); if ( Delete(L, P)==false ) printf(" Deletion Error.\n"); if ( Insert(L, 0, P)==false ) printf(" Insertion Error: 0 is not in.\n"); } return 0; } List MakeEmpty() { List p; p = (List)malloc(sizeof(struct LNode)); p->Last = -1; return p; } Position Find( List L, ElementType X ) { for(int i=0;i<=L->Last;i++) { if(L->Data[i] == X) return i; } return ERROR; } bool Insert( List L, ElementType X, Position P ) { if(L->Last == MAXSIZE-1) { printf("FULL"); return false; } if(P<0 || P>L->Last+1) { printf("ILLEGAL POSITION"); return false; } L->Last++; for(int i=L->Last;i>=P+1;i--) { L->Data[i] = L->Data[i-1]; } L->Data[P] = X; return true; } bool Delete( List L, Position P ) { if(P<0 || P>L->Last ) { printf("POSITION %d EMPTY",P); return false; } if(L->Last ==0) { L->Last--; return true; } for(int i=P;i<=L->Last-1;i++) { L->Data[i] = L->Data[i+1]; } L->Last--; return true; }
6-3 求链式表的表长
int Length( List L ) { List p = L; int ccount = 0; while(p) { ccount++; p = p->Next; } return ccount; }
6-4 查找链表第k个数
ElementType FindKth( List L, int K ) { List p = L; while(K && p) { K--; if(K==0) return p->Data; p = p->Next; } return ERROR; }