Presentation is loading. Please wait.

Presentation is loading. Please wait.

프로그래밍2 및 실습 Sort Code 2016. 10. 25 전명중.

Similar presentations


Presentation on theme: "프로그래밍2 및 실습 Sort Code 2016. 10. 25 전명중."— Presentation transcript:

1 프로그래밍2 및 실습 Sort Code 전명중

2 int main(int argc, const char * argv[]) {
listNode *L; L = addFrontNode(L, "JEON", 95); L = addFrontNode(L, "PARK", 90); L = addFrontNode(L, "KANG", 42); L = addFrontNode(L, "LEE", 80); L = addFrontNode(L, "CHOI", 50); showAllInList(L); printf("[selection] \n"); L = selectionSortByGrade(L); printf("[bubble] \n"); L = bubbleSortByGrade(L); return 0; } typedef struct ListNode{ char *name; int grade; struct ListNode *link; } listNode; listNode* bubbleSortByGrade(listNode *); listNode* selectionSortByGrade(listNode *); int getListSize(listNode *); void showAllInList(listNode *); listNode* addFrontNode(listNode *, char *, int); listNode* createNode(char *, int);

3 Create Node listNode* createNode(char *name, int grade){
listNode* newNode = (listNode *)malloc(sizeof(listNode)); newNode->name = name; newNode->grade = grade; newNode->link = NULL; return newNode; }

4 Add Node to List listNode* addFrontNode(listNode *L, char *name, int grade){ // make a new node listNode *newN = createNode(name, grade); // if first node if( L == NULL ){ L = newN; return L; } // if existing list, add to the first position. newN->link = L;

5 Add Node to List & get Size
void showAllInList(listNode *L){ listNode *temp = L; int i = 0; while (temp != NULL) { printf("[%d] %s : %d\n", i++, temp->name, temp->grade); temp = temp->link; } int getListSize(listNode *L){ listNode *temp = L; int i = 0; while (temp != NULL) { i++; temp = temp->link; } return i;

6 Selection Sort listNode* selectionSortByGrade(listNode *L){
listNode *curr = L; while ( curr != NULL ) { // last node if ( curr->link == NULL ){ break; } listNode *temp = curr->link; listNode *min = temp; while ( temp != NULL ) { if (min->grade > temp->grade){ min = temp; temp = temp->link; if ( curr->grade > min->grade ){ int tmpGrade = min->grade; min->grade = curr->grade; curr->grade = tmpGrade; curr = curr->link; return L; Selection Sort

7 Bubble Sort listNode* bubbleSortByGrade(listNode *L){
int len = getListSize(L); // if length of list is less than 1 if (len <= 1) return L; listNode *p1 = L; listNode *p2 = L->link; for ( int i = len - 1; i >= 0; i-- ){ // init p1 = L; p2 = L->link; for ( int j = 0; j < i; j++ ){ if ( p1->grade > p2->grade ){ // swap int tmp = p1->grade; p1->grade = p2->grade; p2->grade = tmp; }// if // move next position p1 = p1->link; p2 = p2->link; } Bubble Sort


Download ppt "프로그래밍2 및 실습 Sort Code 2016. 10. 25 전명중."

Similar presentations


Ads by Google