예제 #1
0
    void
heap_sort(
        void* base,
        size_t size,
        size_t count,
        int (*compare)(const void*, const void*))
{
    sort_t s;
    char* tail;

    s.head = (char*)base;
    s.size = size;
    s.count = count;
    s.compare = compare;

    /* Make heap. */
    {
        int i;
        for (i = count - 1; i >= 0; --i) {
            insert_heap(&s, i);
        }
    }

    for (tail = s.head + size * (count - 1); s.head < tail; tail -= s.size)
    {
        swap(s.head, tail, s.size);
        s.count -= 1;
        insert_heap(&s, 0);
    }
}
예제 #2
0
//handles token k+1 when the first k tokens are all the same
void handle_second_distinct(Estimator_type* est, c_a* token)
{
  double r;
  Sample_type* cur;
  est->two_distinct_tokens = 1;
  for(int i = 0; i < est->c; i++)
  {
    cur = est->samplers[i];
	r = prng_float(est->prng);
	if(r < cur->t0)
	{
	  cur->val_c_s1 = cur->val_c_s0;
	  cur->c_s1 = cur->c_s0;
	  cur->t1 = cur->t0;
	  
	  cur->val_c_s0 = 1;
	  cur->c_s0=token;
	  cur->t0=r;
	}
	else
	{
	  cur->val_c_s1 = 1;
	  cur->c_s1 = token;
	  cur->t1 = r;
	}
	reset_wait_times(cur, est);
	//must reset wait times before inserting into prim heap or
	//incrementing prim samplers (because increment_prim_samplers() handles
	//insertion/restoring heap property in c_s0's heap and est's bheapneeds 
	//and hence needs the wait times to be set properly as precondition
	insert_heap(est->prim_heap, cur);
	increment_prim_samplers(cur->c_s0, est->bheap, cur);
	increment_backup_samplers(cur->c_s1);
  }
}
예제 #3
0
//called by Estimator_Update to handle first token in stream
//slightly more efficient than just using handle_nondistinct
static void naive_handle_first(Naive_Estimator_type* est, c_a* first)
{
  for(int i = 0; i < est->c; i++)
  {
    est->samplers[i]->c_s0=first;
	est->samplers[i]->val_c_s0=1;  
	est->samplers[i]->t0=prng_float(est->prng);
	naive_increment_prim_samplers(first);
	naive_reset_wait_times(est->samplers[i], est);
	insert_heap(est->prim_heap, est->samplers[i]);
  }
}
예제 #4
0
int manageContextSwitching( RunningState* run_state, Heap* ready_queue,
                            DeviceSet* device_set, ConfigData* configurations,
                            ActivityLog* activity_log )
{
    // case: we have a process that was running
    if( run_state->process_is_running )
    {
        // move the process to its next task and place the process in
        // the back of the ready queue
        increment_iterator( &(run_state->currently_running_process.job_list) );
        insert_heap( ready_queue, run_state->currently_running_process,
                     configurations->cpu_scheduler );
        run_state->process_is_running = false;
    }

    // get one from the queue if possible
    if( !is_Heap_empty( ready_queue ) )
    {
        // pop the item out of the queue
        run_state->currently_running_process =
            remove_PCB_from_Heap( ready_queue );
        run_state->process_is_running = true;
    }
    // case: there are no items to remove from the queue
        // leave the run state empty, with no process running

    // perform context switches until we get a processor destined
    // for the CPU or we are out of processeses to get
    while( ( get_listTask( &(run_state->currently_running_process.job_list) ).task_number != PROCESS ) &&
           !is_Heap_empty( ready_queue ) )
    {
        // send the process to the I/O queue it is destined for
        sendToIoQueue( &(run_state->currently_running_process), device_set,
                       activity_log );

        // get one from the queue if possible
        if( !is_Heap_empty( ready_queue ) )
        {
            // pop the item out of the queue
            run_state->currently_running_process =
                remove_PCB_from_Heap( ready_queue );
        }
        // case: there are no items to remove from the queue
            // leave the run state empty, with no process running
    }

        // now we will either have a process ready for the CPU or all
        // processes will be doing their I/O operations
        // (or the simulator run will be just about over)
}
예제 #5
0
int main (int argc, char *argv[])
{
   puzzle best_soln;
   int    best_cost;
   int    i;
   puzzle s, t, u;
   int    lbsf;

   initialize_heap();
   get_puzzle(&s);
   startTime = clock()/1000;
   print_puzzle(s);
   insert_heap(s);
   best_cost = 999;
   lbsf = 0;
   while(heap_size > 0) {
      u = delete_heap();
      if (u.lower_bound > lbsf) {
         lbsf = u.lower_bound;
      }
      if (u.lower_bound >= best_cost) break;
      if (solved(u)) {
         if (u.lower_bound < best_cost) {
            s = u;
            best_cost = u.lower_bound;
         }
      } else {
         for (i = 0; i < possible_moves[u.hole]; i++) {
            t = make_move (u, i);
            insert_heap (t);
         }
      }
   }
   print_solution (s);
   printf("Finished in %i milliseconds.\n", clock()/1000 - startTime);
}
예제 #6
0
void sort_heap(int arr[], int len) {
    // construct heap
    int i;
    for (i = 0; i < len; ++i) {
        printf("heap: \n");
        insert_heap(heap, i, arr[i]);
        array_display(heap, 1+i+1);
    }
    // sort
    for (i = 0; i < len; ++i) {
        printf("sort: \n");
        arr[i] = heap_pop(len-i);
        array_display(arr, i+1);
    }
}
예제 #7
0
void decrease_key( int item )
{
	int i = find_key( item );

	if ( i == -1 )
	{
		insert_heap( item );
	}

	while ( i > 1 && value( heap[i / 2] ) > value( item ) )
	{
		heap[i] = heap[i / 2];
		i = i / 2;
	}

	heap[i] = item;
}
예제 #8
0
파일: 5.c 프로젝트: cheerayhuang/Garner
int get_min_kvalues(int *max_heap)
{
    int n = 0;
    int data = 0;
    int k = 0;
    int count = 0;

    FILE *fin = fopen("5.in", "r");
    if (fin == NULL) {
        return -1;
    }

    fscanf(fin, "%d %d", &n, &k);

    while(fscanf(fin, "%d", &data) != EOF) {

        if (count < k) {

            if (insert_heap(max_heap, data, count) != 0) {
                return -1;
            }
            ++count;
        }

        if (count == k && data < max_heap[0]) {

            max_heap[0] = data;
            keep_max_heap(max_heap, 0, k);
        }
    }

    if (ferror(fin) != 0) {
        return -1;
    }

    fclose(fin);

    for (count = 0; count < k; ++count) {
        fprintf(stdout, "%d ", max_heap[count]);
    }
    fprintf(stdout, "\n");

    return 0;
}
예제 #9
0
파일: heap.c 프로젝트: shoutrain/algorithm
static void _run() {
	init_heap();
	insert_heap(1);
	_printAll();
	insert_heap(2);
	_printAll();
	insert_heap(3);
	_printAll();
	insert_heap(4);
	_printAll();
	insert_heap(5);
	_printAll();
	insert_heap(6);
	_printAll();
	insert_heap(7);
	_printAll();
}
예제 #10
0
int sendToIoQueue( PCB* process, DeviceSet* device_set,
                   ActivityLog* activity_log )
{
    // variables
    int io_task_type =
        (get_listTask( &(process->job_list)  ) ).task_number;
    Device* requested_device = NULL;

    // assert a precondition that the process is not a processing one
    assert( io_task_type != PROCESS );

    // pick which device the process needs to use
    requested_device = &(device_set->device_number[io_task_type]);

    // add the device to the appropriate I/O queue where it will be handled
    // in I/O management
     insert_heap( &(requested_device->waiting_queue),
                  *process, FIFO_HEAP );
}
예제 #11
0
int main()
{
    int a[MAX_SIZE];
    int n=0,ch,item;
    while(1)
    {
        printf("\n1. Insert\n2. Delete\n3. Display\n4. Exit\n Enter your choice : ");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1:printf("Enter the item to insert : ");
                    scanf("%d",&item);
                    n=insert_heap(item,a,n);break;
            case 2:n=delete_heap(a,n);break;
            case 3:display(a,n);break;
            case 4:return 0;
            default:printf("Invalid Choice");
        }
    }
    return 0;
}
예제 #12
0
//process a new token read from the stream
void Naive_Estimator_Update(Naive_Estimator_type * est, int token)
{
  est->count++;
  
  Freq_Update(est->freq, token);
  //end of Misra-Gries part of algorithm

  //increment count of token, sets processing to 1
  c_a* counter = naive_increment_count(est->hashtable, token);
  
  if(est->count == 1)
  {
    naive_handle_first(est, counter);
	return;
  }
  
  Sample_type* min;
  while(((Sample_type*) peek_min(est->prim_heap))->prim <= est->count)
  {
    min=delete_min(est->prim_heap);
	if(min->prim < est->count)
	{
	  fprintf(stderr, "a sampler's prim decreased. fatal error\n");
	  fprintf(stderr, "min->c_s0_key: %d, min->prim %d, est->count %d\n", 
	                   min->c_s0->key, min->prim, est->count);
	  exit(1);
	}
	naive_decrement_prim_samplers(est->hashtable, min->c_s0);
	naive_increment_prim_samplers(counter);
	//have min take a new sample
	min->c_s0 = counter;
	min->val_c_s0 = counter->count;
	min->t0 *= prng_float(est->prng);
	naive_reset_wait_times(min, est);
	//reinsert min into primary heap
	insert_heap(est->prim_heap, min);
  }
  naive_done_processing(est->hashtable, counter);
}
예제 #13
0
int manageIoDevice( Device* device, Heap* ready_queue,
                    ActivityLog* activity_log )
{
    // variables
    char action_message[STD_STR_LEN];
    PCB temp;

    // case: an I/O completion interrupt has been raised
    if( device->data.interrupt_flag )
    {
        // time this action
        stopwatch( 's', IO_TIMER );

        // kill the I/O simulating thread
        pthread_join( device->data.thread_id, NULL );

        // release the device from the process, load it into the main
        // scheduler
        device->data.interrupt_flag = false;
        device->data.in_use = false;
        insert_heap( ready_queue, *(device->working_process), FIFO_HEAP );
        device->working_process = NULL;

        // log this action
        sprintf( action_message, "%s action completed for process %d - "
                                 "process placed back in main scheduler",
                 device->name, device->working_process->pid );
        logEvent( activity_log, SYSTEM, action_message,
                   stopwatch( 'x', IO_TIMER ) );
    }
    // case: an I/O processed is running and needs to be managed
    else if( device->data.in_use )
    {
        // log the maintenance of the process (simulate with a short wait)
        stopwatch( 's', IO_TIMER );
        usleep( IO_MANAGEMENT_TIME );
        sprintf( action_message,
                 "I/O maintnenance: %s still in use by process %d",
                 device->name, device->working_process->pid );
        logEvent( activity_log, SYSTEM, action_message,
                   stopwatch( 'x', IO_TIMER ) );
    }

    // case: an I/O process is wating to run and the I/O device is free
    //       (it is possible that the device was previously freed previously)
    if( !(device->data.in_use) && !is_Heap_empty( &(device->waiting_queue ) ) )
    {
        // start the I/O process on this device
        stopwatch( 's', IO_TIMER );
        temp = remove_PCB_from_Heap( &(device->waiting_queue) );
        device->working_process = &temp;

        // startup the independent I/O action (simulated of course)
        pthread_attr_init( &(device->data.attribute) );
        pthread_create( &(device->data.thread_id), &(device->data.attribute),
                        conductIoProcess, (void*) &(device->data) );

        // log the action
        sprintf( action_message, "Starting process %d on %s",
                 device->working_process->pid, device->name );
        logEvent( activity_log, SYSTEM, action_message,
                  stopwatch( 'x', IO_TIMER ) );
    }
}
예제 #14
0
void dijkstra( int lift, int start )
{
	int i, l, v, pre;

	bool intree[MAXLIFTS][MAXFLOORS];

	memset( intree, false, sizeof( intree ) );

	distance[lift][start] = 0;
	
	heap[1] = lift * 100 + start;
	heap_size = 1;
	
	l = lift, v = start;

	while ( 1 )
	{
		if ( heap_size == 0 )
		{
			break;
		}
		
		extract_min( l, v );
		
		intree[l][v] = true;		
		
		for ( i = 0; i < MAXFLOORS; ++i )
		{
			if ( a[l][v][i] != -1 )
			{				
				if ( a[l][v][i] + distance[l][v] < distance[l][i] )
				{								
					pre = distance[l][i];

					distance[l][i] = a[l][v][i] + distance[l][v];

					if ( pre == INF )
					{
						insert_heap( l * 100 + i );
					}
					else
					{
						decrease_key( l * 100 + i );
					}					
				}				
			}
		}
		
		if ( v != 0 )
		{
			for ( i = 0; i < lifts; ++i )
			{		
				if ( r[i][v] == true && distance[l][v] + 60 < distance[i][v] )
				{
					pre = distance[i][v];

					distance[i][v] = distance[l][v] + 60;

					if ( pre == INF )
					{
						insert_heap( i * 100 + v );
					}
					else
					{
						decrease_key( i * 100 + v );
					}
					
				}
			}
		}						
	}			
}
예제 #15
0
//process a new token read from the stream
void Estimator_Update(Estimator_type * est, int token)
{
  int old_cs0pos, old_backupminuswait, wait;
  est->count++;
  
  Freq_Update(est->freq, token);
  //end of Misra-Gries part of algorithm

  //In the case that a sampler is scheduled to take a new backup and
  //primary sample at the same time, we should use more random bits to
  //break the tie. But for now, for simplicity, we'll break all such
  //ties by having the sampler take a new *primary* sample

  //increment count of token, sets processing to 1
  c_a* counter = increment_count(est->hashtable, token);
  
  //check for special cases
  if(est->count == 1)
  {
    est->first = counter;
    handle_first(est, counter);
	return;
  }
  if(counter->count == est->count)
  { 
    handle_nondistinct(est, counter);
	return;
  }
  if(est->two_distinct_tokens == 0)
  {
    handle_second_distinct(est, counter);
	//indicate that we are done for the time being with two
	//distinct tokens in the stream so they can be removed from
	//the hashtable if no samplers are sampling them
	done_processing(est->hashtable, counter);
	done_processing(est->hashtable, est->first);
	return;
  }
  
  //only restore heap prop if samplers have been put in bheap
  restore_bheap_property(est->bheap, counter->backup_pos);
  
  Sample_type* min;
  c_a* old_c_s1 = NULL;

  while(((Sample_type*) peek_min(est->prim_heap))->prim <= est->count)
  {
    min=delete_min(est->prim_heap);
	if(min->prim < est->count)
	{
	  fprintf(stderr, "a sampler's prim decreased. fatal error\n");
	  fprintf(stderr, "min->c_s0_key: %d, min->prim %d, est->count %d\n", 
	                   min->c_s0->key, min->prim, est->count);
	  exit(1);
	}
	//have min take a new primary sample
	if(min->c_s0 == counter)
	{
	  min->val_c_s0 = counter->count;
	  min->t0 *= prng_float(est->prng);
	  //resample primary and backup wait times using new values of t0 and t1
	  reset_wait_times(min, est);
	  restore_c_a_heap_property(min->c_s0->sample_heap, min->c_s0_pos);
	  restore_bheap_property(est->bheap, min->c_s0->backup_pos);
	}
	else
	{
	  old_c_s1 = min->c_s1;
	  min->c_s1 = min->c_s0;
	  min->val_c_s1 = min->val_c_s0;
	  min->t1 = min->t0;
	  min->c_s0 = counter;
	  min->val_c_s0 = counter->count;
	  min->t0 *= prng_float(est->prng);
	  
	  //resample primary and backup wait times using new values of t0 and t1
	  old_cs0pos = min->c_s0_pos;
	  old_backupminuswait = min->backup_minus_delay;
	  reset_wait_times(min, est);
	  
	  //increment backup samplers for c_s1 first, b/c if we decremented 
	  //prim samplers first and min was the only primary sampler of c_s1 and 
	  //c_s1 had no backup samplers, then c_s1 would be removed from the hashtable
	  //which we don't want. Note increment_backup_samplers does *not* change
	  //min->c_s0_pos, so the subsequent call to decrement_prim_samplers will work fine
	  //when it tries to remove min from c_s1's heap of samplers
	  increment_backup_samplers(min->c_s1);
	  decrement_backup_samplers(est->hashtable, old_c_s1);
	  decrement_prim_samplers(est->hashtable, min->c_s1, est->bheap, min);	  
	  increment_prim_samplers(counter, est->bheap, min);
	}
	//reinsert min into primary heap
	insert_heap(est->prim_heap, min);
  }
	
  c_a* min2 = peek_min_bheap(est->bheap);
  min = peek_min_c_a_heap(min2->sample_heap);

  double r1;
  while(min->backup_minus_delay + min2->count <= est->count)
  {
	if(min->backup_minus_delay + min2->count < est->count)
	{ //error check
	  fprintf(stderr, "error: sampler's backup wait time decreased\n");
	  fprintf(stderr, "bminusd %d, min2->count %d est->count %d\n", 
	          min->backup_minus_delay, min2->count, est->count);
	  exit(1);
	}

	decrement_backup_samplers(est->hashtable, min->c_s1);
	increment_backup_samplers(counter);
	min->t1 -= prng_float(est->prng) * (min->t1-min->t0);
	min->c_s1 = counter;
	min->val_c_s1 = counter->count;
	
	//recalculate just min's backup wait time
	r1 = prng_float(est->prng);
	if(r1 == 0) min->backup_minus_delay = est->count + 1 - min->c_s0->count;
	else
	{
	  if(min->t1-min->t0 == 0)
	  { //t0 == t1 should cause longest possible wait time
		min->backup_minus_delay = MAX_WAIT-min->c_s0->count;
	  }
	  else
	  {
	    wait = ceil(log(r1)/log(1.0-(min->t1-min->t0)));
								
	    if(wait < 0 || wait > MAX_WAIT) //check for overflow
	      min->backup_minus_delay = MAX_WAIT-min->c_s0->count;
	    else
	      min->backup_minus_delay = wait + est->count - min->c_s0->count;
	  }
	}
	//fprintf(stderr, "%d ", min->backup_minus_delay);

	//put min in proper position in its primary sample's heap
	restore_c_a_heap_property(min->c_s0->sample_heap, min->c_s0_pos);

	//put min's primary sample in proper position in backup heap
	restore_bheap_property(est->bheap, min->c_s0->backup_pos);
	
	min2 = peek_min_bheap(est->bheap);
    min = peek_min_c_a_heap(min2->sample_heap);
  }	
  done_processing(est->hashtable, counter);
}